How does one malloc a struct which is inside another struct?
I would also like to malloc an array of items inside a struct and then realloc this array when needed, how i
It's not very readable but sometimes people create a structure with a count member and a final single-element array member. There then is a special factory method that allocates enough space so that you can write to count elements in the array. Obviously the array member can be of any type.
typedef struct {
int count;
int elements[1];
} int_array;
int_array* allocate_int_array(int count)
{
int_array* mem = (int_array*)malloc(sizeof(int_array) + (count - 1) * sizeof(int));
if (mem)
mem->count = count;
return mem;
}