Allocate / free dynamic array of pointers to structure in C
Let's say I have the following two structure definitions in C.
struct child {
int x;
};
struct Yoyo {
struct child **Kids;
};
How I would decide to allocate memory for children.
let's say for example I have a Yoyo_create () function.
static struct Yoyo * yoyo_create() {
int n = 32000;
struct Yoyo *y;
y = malloc(sizeof( *Yoyo));
y->Kids = malloc(n*sizeof(*Child));
for (i = 0 ; i < n ; i ++) { y->Kids[i] = NULL; }
}
and then destroy the children in some sort of "destructor function" I would do.
void yoyo_destroy(struct yoyo *y)
{
free(y->Kids);
free(y);
}
It makes sense?
+3
source to share
2 answers