如何使用一个 malloc 以连续的方式分配 3D、4D、5D 数组并访问各个项目?
是这样的:
int* array = malloc(sizeof(int) * width * height);
int item = array[x + y * width];
最佳答案
3D 数组是 2D 数组的数组。 4D 数组是 3D 数组的数组。你只需乘以你的其他维度。例如,一个 3D 数组可以这样分配:
int *array = malloc(sizeof(int) * width * height * depth);
可以通过乘以你的其他维度来制作 4D 数组:
int *array = malloc(sizeof(int) * width * height * depth * other_dimension);
对于 5D、6D 等数组依此类推。
假设您可以访问数组的宽度和高度,您可以使用类似这样的方法访问元素(对于 3D 数组,易于扩展):
int get_element(int x, int y, int z)
{
return array[(z * width * height) + (y * width) + x];
}
对于 4 维数组:
int get_element(int x, int y, int z, int dimension_4)
{
return array[(dimension_4 * width * height * depth) + (z * width * height) + (y * width) + x];
}
关于c++ - 如何分配和访问 3D、4D、5D 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33041606/