C++动态申请数组

原文:http://stackoverflow.com/questions/3904304/3d-array-c-using-int-operator/3904564#3904564

To create dynamically 3D array of integers, its 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 a int-pointer which will point to a chunk of memory where integers can be stored.

2D array: You may use solution of above 1D array to create 2D array. First crate a pointer which should point to a memory block where only other integeral pointers are hold which ultimately points to actual data. since our first pointer point to a array of pointer 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. Apply the same logic as 2D array. Diagram in question explains all. First array will be pointer-to-pointer-to-pointer (int*** - since it points to double pointers). 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;               

        }   

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值