3D array C++ using int [] operator

后端 未结 7 1885
长发绾君心
长发绾君心 2020-12-15 09:03

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

\

7条回答
  •  一个人的身影
    2020-12-15 09:28

    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

提交回复
热议问题