float **Array2D_Float( int nRows, int nCols)
{
float **dynamicArray2d_float;
dynamicArray2d_float = newfloat*[nRows];
dynamicArray2d_float[0] = newfloat[nRows * nCols];
for( int i = 0 ; i < nRows ; i++ )
{
if (i>0)
dynamicArray2d_float[i] = dynamicArray2d_float[i-1] + nCols;
for( int j = 0 ; j < nCols ; j++ )
dynamicArray2d_float[i][j]=0;
}
return dynamicArray2d_float;
}
In my main program I have the following code:
float **lon2D = Array2D_Float(gjdm,gidm);
gjdm and gidm are two integers that come from an inputfile.
I know that I have to free the memory with delete [].
But my question is do I have to deallocate the memory of both arrays?
Do I have to free the memory pointed to by dynamicArray2d_float?
If yes where can I do this because I cannot do this in the function.
Do I have to free the memory pointed to by lon2D?
But my question is do I have to deallocate the memory of both arrays?
You have to delete[] everything you new[]. Since you allocated both dynamicArray2d_float and dynamicArray2_float[0], you'll need to delete[] both of those.
Do I have to free the memory pointed to by dynamicArray2d_float?
If yes where can I do this because I cannot do this in the function.
Do I have to free the memory pointed to by lon2D?
You don't have to use dynamicArray2d_float exactly.
You're not deleting that specific pointer... you're deleting what the pointer points to. Therefore any pointer that points to the same place can be used instead.
Since you are passing this to lon2D, you could do this:
1 2 3 4 5 6
float** lon2D = Array2D_Float(bjdm,gidm);
// use lon2D here
delete[] lon2d[0];
delete[] lon2d;
Although -- passing ownership like this is a bad idea, as it makes it unclear who the owner is and who is responsible for cleanup. You're better off objectifying so that you don't have to pass pointers around. Doing this kind of thing is what causes memory leaks.
Anything that is allocated using new or new[] has to be deallocated by delete or delete[] or you'll have a memory leak. To deallocate what you have there, you need to delete[] dynamicArray2d_float[0] and dynamicArray2d_float IN THAT ORDER. If they aren't deleted in that order, you'll get a SEGFAULT error.
To be honest, though, I don't think you should make 2d arrays this way. Whenever I need a 2d array, I usually make a class that treats a 1d array as a 2d array, using the equation y*width+x to get the index. Something like this:
(sorry I used spaces instead of tabs - I'm on my phone)
This struct makes it really easy to handle 2d arrays, and is easily expanded (you could make a function to resize it, for example)