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


you don't need these lines

y->Kids = malloc(n*sizeof(*Child)); and <br>
free(y->Kids); 

      



because your y contains the structure of children in it. And apart from these, you go well

+2


source


y = malloc (sizeof (struct Yoyo));



y-> Children = malloc (n * sizeof (struct Child));

0


source







All Articles