I have a structure , which present my element of data
struct myElement
{
int field1;
int field2;
int field3;
};
another structure, which contain array of this elements and some another data
struct myArray
{
struct myElement *elements;
int someData;
};
and I need to have array of this arrays like that
struct myArray *myMatrix;
But I have a problem with memory allocation. Count of elements in myArray’s can be different, in myMatrix too, so I need to allocate memory dynamicaly. What is the corret way to allocate and deallocate memory in this situation?
Here’s a small example of how you would allocate (
malloc) and deallocate (free) a dynamicstruct myElementarray in astruct myArray. Note also that you will need to keep track of the size of the array, so I addedsize_t elements_len;tostruct myArray(excuse the combination of camelCase and underscores – I use underscores in C, but didn’t want to modify your identifiers):Apply similar logic in order to have a dynamic array of
struct myArray. You wouldmallocenough memory for X amount ofstruct myArrays, thenforeachstruct myArrayelement in that array, you would callallocate_elements. Then iterate through each element in the array once you’re done with it and callfree_elements.