问题描述
我翻译一些MATLAB code到C和我转换脚本大量使用三维阵列与10 * 100 * 300的复杂项目。阵列的大小还取决于传感器的输入,理想阵列应动态分配的。到目前为止,我已经试过两种方法首先是沿着线一台一维数组
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偏移(INT X,INT Y,INT Z){回报(Z * xSize * ySize)+(Y * xSize)+ X; }
int offset( int x, int y, int z ) { return ( z * xSize * ySize ) + ( y * xSize ) + x ; }
这篇关于MALLOC在C 3维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!