Deallocation of 3 dimensional array

2020-06-06 05:01发布

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?

5条回答
Root(大扎)
2楼-- · 2020-06-06 05:27

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?

查看更多
趁早两清
3楼-- · 2020-06-06 05:30

Yes. (What else am I meant to say)

查看更多
该账号已被封号
4楼-- · 2020-06-06 05:33

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);
  }
}
查看更多
该账号已被封号
5楼-- · 2020-06-06 05:38

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.

查看更多
疯言疯语
6楼-- · 2020-06-06 05:43

Also you can implement a wrapper class for std::vector

查看更多
登录 后发表回答