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
initalize struct with new operator?
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.
SMonster tempOnStack = SMonster { "Michael", 100, 5, .25, "Revolver", .50, 20, 5 };
SMonster* onHeap = malloc(sizeof(SMonster));
*onHeap = tempOnStack ;
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.
[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
Popular Topics
Advertisement