2

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?

drjrm3
  • 4,474
  • 10
  • 53
  • 91

5 Answers5

3

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.

ksming
  • 1,422
  • 1
  • 16
  • 26
  • Note also the performance benefits in having a single pair of `new/delete` calls. There may likely be further performance benefits through using a contigous block rather than a potentially scattered collection of small blocks. – Keith Sep 16 '11 at 05:00
  • i thought about doing this actually. which would benefit more from locality of reference more? – drjrm3 Sep 16 '11 at 14:55
2

Yes. (What else am I meant to say)

flight
  • 7,162
  • 4
  • 24
  • 31
1

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?

K-ballo
  • 80,396
  • 20
  • 159
  • 169
0

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);
  }
}
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

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

fasked
  • 3,555
  • 1
  • 19
  • 36