Sign in to follow this  

initalize struct with new operator?

This topic is 2392 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

im a little confused on how to initialize a struct once i allocate it on the heap using the new operator...for example how do this


*SMonster firstMonster = new SMonster { "Michael", 100, 5, .25, "Revolver", .50, 20, 5 }; <---- i want to allocate 1 struct call of SMonster and initialize it with the values in the brackets once made

Share this post


Link to post
Share on other sites
Or wrap it in a function:

[source lang="c"]
Monster *MakeMonster(const char *name,int legs,float size)
{
Monster *m=(Monster*)malloc(sizeof(Monster));

strcpy(m->name,name);
m->legs=legs;
m->size=size;

return m;
}

void f()
{
Monster *m=MakeMonster("Paul",8,2.0f);

// blah

free(m);
}
[/source]

That's about the closest you can get to a constructor for a struct in C.

Share this post


Link to post
Share on other sites

This topic is 2392 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this