3D array C++ using int [] operator

Marco Aviles picture Marco Aviles · Oct 11, 2010 · Viewed 20.6k times · Source

I'm new to C/C++ and I've been cracking my head but still got no idea how to make an "structure" like this

alt text

It's supposed to be a 3D dynamic array using pointers.

I started like this, but got stuck there

  int x=5,y=4,z=3;
  int ***sec=new int **[x];

It would be enough to know how to make it for a static size of y and z;

Please, I'd appreciate that you help me.

Thanks in advance.

Answer

Manish Shukla picture Manish Shukla · Oct 11, 2010

To create dynamically 3D array of integers, it's better you understand 1D and 2D array first.

1D array: You can do this very easily by

const int MAX_SIZE=128;
int *arr1D = new int[MAX_SIZE];

Here, we are creating an int-pointer which will point to a chunk of memory where integers can be stored.

2D array: You may use the solution of above 1D array to create a 2D array. First, create a pointer which should point to a memory block where only other integer pointers are held which ultimately point to actual data. Since our first pointer points to an array of pointers so this will be called as pointer-to-pointer (double pointer).

const int HEIGHT=20;
const int WIDTH=20;

int **arr2D = new int*[WIDTH];  //create an array of int pointers (int*), that will point to 
                                //data as described in 1D array.
for(int i = 0;i < WIDTH; i++){
      arr2D[i] = new int[HEIGHT]; 
}

3D Array: This is what you want to do. Here you may try both the scheme used in above two cases. Apply the same logic as 2D array. Diagram in question explains all. The first array will be pointer-to-pointer-to-pointer (int*** - since it points to double pointers). The solution is as below:

const int X=20;
const int Y=20;
const int z=20;

int ***arr3D = new int**[X];
for(int i =0; i<X; i++){
   arr3D[i] = new int*[Y];
   for(int j =0; j<Y; j++){
       arr3D[i][j] = new int[Z];
       for(int k = 0; k<Z;k++){
          arr3D[i][j][k] = 0;
       }
   }
}