initalize struct with new operator?

Started by
6 comments, last by Aardvajk 12 years, 11 months ago
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
Advertisement
You can give a struct a constructor with an initialization list, just like a class.
is that only C++ or also legal in C?
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.
how would you go about this with malloc() then?
SMonster tempOnStack = SMonster { "Michael", 100, 5, .25, "Revolver", .50, 20, 5 };
SMonster* onHeap = malloc(sizeof(SMonster));
*onHeap = tempOnStack ;
Call malloc to dynamically allocate for your struct. Then set the members manually.
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.

This topic is closed to new replies.

Advertisement