# Dynamic 3D array allocation

• 11-20-2001
Vulcan
Dynamic 3D array allocation
Using new & delete, how to I dynamically allocate & deallocate a 3-dimensional array?

-Vulcan
• 11-21-2001
gliptic
If all the dimensions should be dynamical, you could do like this:

char *dynarray;
long dimx, dimy, dimz;

//macro for calculating the position of a coordinate in the array:
#define getarr(x,y,z) dynarray[x+y*dimx+z*dimx*dimy]

//code for declaring and using the array:

dimx = 5; dimy = 5; dimz = 5;

dynarray = new char[dimx*dimy*dimz];

getarr(0,0,0) = 0;

delete [] dynarray;
• 11-21-2001
Vulcan
yeah
Thats how i did do it before, map a 3D array to a 1D space via the same way you showed. but what i wanted to do so if you had a 3D space
[x][y][z]

you could acess the array as such
data[x][y][z]

where data is a ***
pointer to a pointer to a pointer.

-Vulcan
• 11-21-2001
gliptic
You can't do it.
• 11-21-2001
kitten
Quote:

data[x][y][z]
You can't do it.
Wrong! There sure is possible solution. Look at this:
Code:

```const int Xsize = 20; const int Ysize = 30; const int Zsize = 80; char ***3DArray; // Allocating array: 3DArray = new char**[Xsize]; for (int i=0; i<Xsize; ++i) {   3DArray[i] = new char*[Ysize];   for (int j=0; j<Ysize; ++j)  3DArray[i][j] = new char[Zsize]; } // destroying array: for (int i=0; i<Xsize; ++i) {   for (int j=0; j<Ysize; ++j)  delete [] 3DArray[i][j];   delete [] 3DArray[i]; } delete [] 3DArray;```
Now you can access this array with 3DArray[2][5][25]