Something like this should work though it is not a great solution with so many seperate allocations, further down is a better solution. I have tried to make variable names descriptive of what they hold.
int arrayOfSubArrayLengths={9,5,10,50,...};
int lengthOfMyMatrix=something;
myMatrix= (myArray*) malloc( sizeof(myArray) * lengthOfMyMatrix);
for(int i=0; i<lengthOfMyMatrix; ++i)
{
myMatrix[i].elements=new myElement[arrayOfSubArrayLengths];
myMatrix[i].someData=whatever;
}
to delete:
for(int i=0; i<lengthOfMyMatrix; ++i)
{
free( myMatrix[i].elements );
}
free( myMatrix );
However as I said that is not a great solution with so many allocations. It could cause some severe memory fragmentation depending on how large lengthOfMyMatrix is. Also so many calls to the allocator could slow things down depending once again on the size of lengthOfMyMatrix.
Here is a better solution:
int arrayOfSubArrayLengths={9,5,10,50,...};
int lengthOfMyMatrix=something;
int sumOfSubArrayLengths=someNumber;
myArray* fullArray=(myElement*) malloc( sizeof(myElement) * sumOfSubArrayLengths);
myMatrix= (myArray*) malloc( sizeof(myArray) * lengthOfMyMatrix);
int runningSum=0;
for(int i=0; i<lengthOfMyMatrix; ++i)
{
myMatrix[i].elements = &fullArray[runningSum];
runningSum += arrayOfSubArrayLengths[i];
myMatrix[i].someData = whatever;
}
to delete:
free( fullArray );
free( myMatrix );
In this fashion there are only two calls to the allocator no matter the various lengths. So there is far more memory fragmentation and less allocation overhead time.
The one downside to the second method is that if you are not careful with bounds checking it is very easy to corrupt data in the array without knowing since the memory 'belongs' to you and thus the OS will not kick you for an access violation.
mallocandfree- Seth Carnegie