问题描述
我是 C/C++ 的新手,我一直在绞尽脑汁,但仍然不知道如何制作这样的结构"
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
它应该是一个使用指针的 3D 动态数组.
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];
知道如何为 y 和 z 的静态大小制作它就足够了;
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.
提前致谢.
推荐答案
要动态创建 3D 整数数组,最好先了解 1D 和 2D 数组.
To create dynamically 3D array of integers, it's better you understand 1D and 2D array first.
一维数组:您可以通过
const int MAX_SIZE=128;
int *arr1D = new int[MAX_SIZE];
在这里,我们正在创建一个 int 指针,它将指向可以存储整数的一块内存.
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 阵列:这就是您想要做的.在这里您可以尝试上述两种情况下使用的方案.应用与二维数组相同的逻辑.有问题的图表说明了一切.第一个数组将是指针到指针到指针(int*** - 因为它指向双指针).解决方法如下:
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;
}
}
}
这篇关于使用 int [] 运算符的 3D 数组 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!