I am creating a three dimensional array like this:
GLfloat ***tgrid;
//other code in between here
tgrid = new GLfloat**[nx];
for(int i = 0; i < nx; i++)
{
tgrid[i] = new GLfloat*[ny];
for(int j = 0; j < ny; j++)
{
tgrid[i][j] = new GLfloat[nz];
}
}
Does this mean i should deallocate the memory like this:
for(int i = 0; i < nx; i++)
{
for(int j = 0; j < ny; j++)
{
delete [] tgrid[i][j];
}
delete [] tgrid[i];
}
delete [] tgrid;
?
I know that they are supposed to go in "reverse" order but I'm not sure I'm doing it right ... Does this seem correct?
Yes, you have to deallocate them in reverse order. Otherwise you will loose the inner pointers before deallocating them.
Is there any reason why you cannot use a flat array to represent your 3dimensional array? Perhaps Boost.MultiArray, which handles multiple dimensions and allows access to the underlying (flat) array?
Yes. (What else am I meant to say)
Or, you could use
std::vector
and not worry aboutnew
ordelete
:Since my answer is also yes, I will follow up K-ballo's answer with a minimal example of how to use a flat array to store a set of multi-dimension data:
Store the GLfloat pointer and the dimensions as members of your class:
In initlaization function:
You will need to define your indexing scheme consistently for proper read-write:
Deleting is straight forward too since tgrid is only a flat array.
Also you can implement a wrapper class for std::vector