简体   繁体   中英

Deallocation of 3 dimensional array

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?

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:

GLfloat *tgrid;
int nx, ny, nz;

In initlaization function:

void CreateGrid(int x, int y, int z)
{
    nx = x;
    ny = y;
    nz = z;
    tgrid = new GLfloat[nx*ny*nz];
}

You will need to define your indexing scheme consistently for proper read-write:

GLfloat GetValueAt(int x, int y, int z)
{

    return tgrid[ (nx*ny*z) + (nx*y) + x ]; 

}

void SetValueAt(int x, int y, int z, GLfloat value)
{

    tgrid[ (nx*ny*z) + (nx*y) + x ] = value;

}

Deleting is straight forward too since tgrid is only a flat array.

Yes. (What else am I meant to say)

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?

Or, you could use std::vector and not worry about new or delete :

std::vector<std::vector<std::vector<GLfloat> > > tgrid;
tgrid.resize(nx);
for(int i = 0; i < nx; i++) {
  tgrid[i].resize(ny);
  for(int j = 0; j < ny; i++) {
    tgrid[i][j].resize(nz);
  }
}

您也可以为std :: vector实现包装器类

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM