我正在尝试编写一个过程,该过程允许我分配大小为n1*n2*n3的连续内存块,并使用3个索引访问它,就像使用数组一样
int array[n1][n2][n3];
我已经成功地(据我所知)用两个索引管理了这个(见下面的示例)
#include <stdlib.h>
int main() {
// Dimensions
const int n1 = 2;
const int n2 = 2;
int **array;
// Pointers
array = (int **)malloc(n1*sizeof(int *));
// Contiguous chunk of memory of size n1xn2
array[0] = (int *)malloc(n1*n2*sizeof(int));
// Pointer arithmetic
for(int i=0;i<n1;i++) {
array[i] = array[0] + i*n2;
}
array[0][0] = 1;
return EXIT_SUCCESS;
}
但是当我用三个索引尝试类似的构造时,我的过程会抛出一个segfault:
#include <stdlib.h>
int main() {
// Dimensions
const int n1 = 2;
const int n2 = 2;
const int n3 = 2;
int ***array;
// Pointers
array = (int ***)malloc(n1*sizeof(int **));
array[0] = (int **)malloc(n1*n2*sizeof(int *));
// Contiguous chunk of memory of size n1xn2xn3
array[0][0] = (int *)malloc(n1*n2*n3*sizeof(int));
// Pointer arithmetic
for(int i=0;i<n1;i++) {
for(int j=0;j<n2;j++) {
array[i][j] = array[0][0] + i*n2*n3 + j*n2;
}
}
array[0][0][0] = 1;
return EXIT_SUCCESS;
}
我知道还有其他方法来管理连续的内存块。我特别感兴趣的是为什么我的逻辑在上述情况下失败了。