c++ - 如何分配和访问 3D、4D、5D 数组?

标签 c++ visual-c++

如何使用一个 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/

相关文章:

c - 宏扩展 : Argument with Commas

c++ - 在 strlwr() 中使用字符串数据类型

c++ - 在 arduino 上使用 strncat 方法输出错误值

visual-studio-2008 - 具有多个同名源文件的 Visual Studio 项目?

c++ - 在 Visual C++ 2013 中不能为 "Go To Definition"

c++ - 为什么 std::weak_ptr 没有 operator->?

c++ - 错误LNK2019,如何解决? *更新*

c++ - CStatic 自定义控件

c++ - 使用 ifstream 时出现语法错误

c++ - 在模板类中匹配 CRTP