在 C 中分配一个 3 维数组? [英] Malloc a 3-Dimensional array in C?

查看:36
本文介绍了在 C 中分配一个 3 维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些 MATLAB 代码翻译成 C,我正在转换的脚本大量使用了 10*100*300 复杂条目的 3D 数组.数组的大小还取决于传感器的输入,理想情况下应该动态分配数组.到目前为止,我已经尝试了两种方法,第一种是沿着

I'm translating some MATLAB code into C and the script I'm converting makes heavy use of 3D arrays with 10*100*300 complex entries. The size of the array also depends on the sensor's input, ideally the array should be allocated dynamically. So far I've tried two approaches the first being a flat 1D array along the lines of

value = array[x + (y*xSize) + (z*ySize*xSize)]

使用它会伤害我的大脑.我也试过一个指针数组的数组

Which hurts my brain to use. I've also tried an array of an array of pointers

int main () {
  int ***array = malloc(3*sizeof(int**));
  int i, j;

  for (i = 0; i < 3; i++) {
    *array[i] = malloc(3*sizeof(int*));
    for (j = 0; j < 3; j++) {
      array[i][j] = malloc(3*sizeof(int));
    }
  }

  array[1][2][1] = 10;

  return 0;
}

当我尝试分配数据时会出现段错误.

Which gives a seg fault when I try to assign data.

在一个完美的世界中,我想将第二种方法与数组表示法一起使用,以实现更清晰、更轻松的编程.有没有更好的方法在C中动态分配一个三维数组?

In a perfect world, I'd like to use the second method with the array notation for cleaner, easier programming. Is there a better way to dynamically allocate a three-dimensional array in C?

推荐答案

我会选择第一个选项(单个一维数组),因为它会给你一个内存块来播放,而不是潜在的数千个碎片内存块

I'd go for the first option (the single 1D array) as it will give you a single block of memory to play in rather than potentially thousands of fragmented memory blocks

如果访问数组的正确元素是你的头脑,我会编写一个实用方法来将 x、y、z 位置转换为一维数组的偏移量

If accessing the correct element of the array is doing your head in though, I'd write a utility method to convert x, y, z locations into an offset into the 1D array

int offset(int x, int y, int z) { 
    return (z * xSize * ySize) + (y * xSize) + x; 
}

这篇关于在 C 中分配一个 3 维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆