Using new & delete, how to I dynamically allocate & deallocate a 3-dimensional array?
-Vulcan
Using new & delete, how to I dynamically allocate & deallocate a 3-dimensional array?
-Vulcan
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;
// Gliptic
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
You can't do it.
// Gliptic
Wrong! There sure is possible solution. Look at this:data[x][y][z]
You can't do it.
Now you can access this array with 3DArray[2][5][25]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;
Making error is human, but for messing things thoroughly it takes a computer