Serial memory allocation for an array in a structure in C

I would like to know how to allocate sequential memory for an array of structures inside another structure. Say I have struct1 that has an array of struct2, I would like to have it all in one consecutive block of memory.

I could use malloc to allocate a block, but how would I assign an array memory?

struct1 *set = malloc(sizeof(struct1) + sizeof(struct2)*number_of_structs); set->arr = (struct2*)set + sizeof(struct); //This is probably wrong set->arr[0].data = 1; set->arr[1].data = 2; ... 

Thanks.

+4
source share
2 answers

Use the flexible array element:

 #define NUM_ELEM 42 struct a { /* whatever */ }; struct b { int c; struct ad[]; // flexible array member }; struct b *x = malloc(sizeof *x + NUM_ELEM * sizeof x->d[0]); 
+3
source

This method is used in some Windows APIs; it may look like this:

 struct struct1 { // some members ... struct struct2 arr[1]; } struct1 *set = malloc(sizeof(struct1) + sizeof(struct2) * (number_of_structs-1)); 

set-> arr points to an array of number_of_structs members. struct1 always contains at least one struct2 inside + other struct2 elements in an adjacent memory block.

+2
source

Source: https://habr.com/ru/post/1438731/


All Articles