我对动态分配 3d 数组有点困惑。现在,我只是像这样分配一大块内存:
int height = 10;
int depth = 20;
int width = 5;
int* arr;
arr = new int[height * width * depth];
现在我想更改 3D 数组中的一个值,比如:
//arr[depth][width][height]
arr[6][3][7] = 4;
但是,我不能使用上面的代码来改变这个值。如何使用单个索引访问位置 depth = 6、width = 3、height = 7 的元素?
arr[?] = 4;
有没有更好的方法来动态分配 3D 数组?
最佳答案
C 倾斜的方式是:
int ***arr = new int**[X];
for (i = 0; i < z_size; ++i) {
arr[i] = new int*[Y];
for (j = 0; j < WIDTH; ++j)
arr[i][j] = new int[Z];
}
关于c++ - 动态分配 3d 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10238699/