NoStressZone
NoStressZone

Reputation: 71

Allocate/Deallocate dynamic array of struct pointers in C

say i have the following two struct definitions in C.

struct child { 
int x;
};

struct Yoyo { 
struct child **Kids;
};

How would i go about allocating the memory for Kids.

say for example i have some function Yoyo_create().

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 to destroy the Kids in some "destructor function" i would do.

void yoyo_destroy(struct yoyo *y)
{
free(y->Kids);
free(y);
}

Does that make sense?

Upvotes: 3

Views: 185

Answers (2)

johnslay
johnslay

Reputation: 691

y = malloc(sizeof(struct Yoyo));

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

Upvotes: 0

Bahri
Bahri

Reputation: 36

you don't need these lines

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

because your y contains kids structure in it. And except these , you are going well

Upvotes: 2

Related Questions