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 is this done correctly?
Could you please give an example of declaring a struct and then the above.
Im a little unsure of the order of things.
Would the array within a struct be freed and then the struct itself, must the struct be malloced when it is created and then its fields be malloced/declared etc?
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.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.
To get a single B:
To get an array of B:
A
struct
included inside anotherstruct
is contained by copy, so you would not have to separately malloc it. If thestruct
contains a pointer to anotherstruct
, then you can consider allocating memory for it dynamically.In
struct Rect
, thestruct Point2D
element are inserted intostruct Rect
and you don't have to dynamically allocate memory for them. On the contrary in thestruct LinkedListNode
the next element is referenced by a pointer and the memory must be dynamically allocated.The two version are both useful, depending on the situation. There is no correct way to manage memory, it'll depend on your usage.
This same situation occurs in the case of an array. If your array is statically sized, then it can be directly included in the
struct
. However, if the size can vary, you must store a pointer within thestruct
.The
realloc
function only does a shallow copy, that is pointer value is copied, but not the pointed object. One more time, how you deal with it will depend on your application.