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
The following is an example of nested structs and arrays in structs. You'll notice how the nested elements must be taken care of before you free
the outer struct or else you'll end up with a memory leak.
typedef struct Base Base;
struct Base
{
int x;
};
typedef struct Sample Sample;
struct Sample
{
Base base;
int size;
int *arr;
};
// Create the sample struct
Sample *createSample()
{
Sample sample = malloc(sizeof(Sample));
if(sample == NULL)
{
return NULL;
}
sample->base = malloc(sizeof(Base));
if(sample->base == NULL)
{
free(sample);
return NULL;
}
sample->base->x = 0;
sample->size = 0;
sample->arr = NULL;
return sample;
}
// Adding element to the array
void addItemToSample(Sample *sample, int item)
{
if(sample == NULL)
{
return;
}
int *arr = realloc(sample->arr, sizeof(int) * (sample->size + 1));
if(arr == NULL)
{
return;
}
arr[sample->size++] = item;
sample->arr = arr;
}
// Freeing the struct
void freeSample(Sample *sample)
{
// Free deep elements first
free(sample->base);
free(sample->arr);
// Free outer
free(sample);
}