Free 3D array

I create a three-dimensional array similar to 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 that I should free the memory as follows:

 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 should go "in reverse order", but I'm not sure if I am doing it right ... Does this seem to be right?

+2
source share
5 answers

Since my answer is also yes, I will follow the K-ballo answer with a minimal example of using a flat array to store a multidimensional data set:

Save the GLfloat pointer and sizes as members of your class:

 GLfloat *tgrid; int nx, ny, nz; 

In the initialization 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 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; } 

Deletion happens directly, since tgrid is just a flat array.

+3
source

Yes. (What else did I want to say)

+2
source

Yes, you must release them in the reverse order. Otherwise, you will lose the internal pointers before releasing them.

Is there a reason why you cannot use a flat array to represent your three-dimensional array? Perhaps Boost.MultiArray, which handles multiple dimensions and allows access to the base (flat) array?

+1
source

Or you can 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); } } 
0
source

You can also implement a wrapper class for std :: vector

0
source

Source: https://habr.com/ru/post/1437436/


All Articles