I think I\'ve got a good grasp on how to handle memory in C++ but doing it in C is different I\'m a bit off.
In C++ I\'ve got constructors and destructors, I\'ve got the
I'm not quite sure what you're asking, but C is pretty straightforward:
struct Foo *f0 = malloc(sizeof(*f)); // alloc uninitialized Foo struct
struct Foo *f1 = calloc(1,sizeof(*f)); // alloc Foo struct cleared to all zeroes
//You usually either want to clear your structs using calloc on allocation, or memset. If
// you need a constructor, just write a function:
Foo *Foo_Create(int a, char *b)
{
Foo *r = calloc(1,sizeof(*r));
r->a = a;
r->b = strdup(b);
return r;
}
Here is a simple C workflow with arrays:
struct Foo **foos = NULL;
int n_foos = 0;
...
for(i = 0; i < n_foos; ++i)
{
struct Foo *f = calloc(1,sizeof(*f));
foos = realloc(foos,sizeof(*foos)*++n_foos); // foos before and after may be different
foos[n_foos-1] = f;
}
If you get fancy, you can write macros to help:
#define MALLOCP(P) calloc(1,sizeof(*P)) // calloc inits alloc'd mem to zero
A couple of points: