• Advertisement
Sign in to follow this  

initalize struct with new operator?

This topic is 2461 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
Advertisement
You're using new to allocate your object, so if you're concerned about C then you're already on the wrong way. It has neither constuctors nor new.

Share this post


Link to post
Share on other sites
Call malloc to dynamically allocate for your struct. Then set the members manually.

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
Sign in to follow this  

  • Advertisement