【发布时间】:2019-11-20 20:20:48
【问题描述】:
我有以下代码来分配 3d 数组:
int ***allocate3DArray(int y, int x, int r) {
int ***array = (int ***) malloc(sizeof(int **) * y);
for (int i = 0; i < y; i++) {
array[i] = (int **) malloc(sizeof(int *) * x);
for (int j = 0; j < x; j++) {
array[i][j] = (int *) malloc(sizeof(int) * r);
for (int k = 0; k < r; k++) {
array[i][j][k] = 0;
}
}
}
return array;
}
void free3d(int ***arr, int y, int x, int r) {
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
free(arr[i][j]);
}
free(arr[i]);
}
free(arr);
}
这似乎有点笨拙,如果我 malloc 失败,很难进行错误处理。
也就是说,它非常符合人体工程学,因为我可以像这样简单地访问一个元素:int a = arr[x][y][z]
什么是初始化 3d 数组的最佳方法,既能提供相同的人体工程学灵活性,又能减轻上述一些缺点?
我试过了:
std::array < std::array < std::array < int, radius >, image.cols >, image.rows > houghSpace;
但我得到了一个错误:
error: non-type template argument is not a constant expression
std::array < std::array < std::array < int, radius >, image.cols >, image.rows > houghSpace;
^~~~~~
sobel.cpp:117:49: note: initializer of 'radius' is not a constant expression
sobel.cpp:116:15: note: declared here
const int radius = image.rows / 2;
^
sobel.cpp:117:71: error: expected a type
std::array < std::array < std::array < int, radius >, image.cols >, image.rows > houghSpace;
^
sobel.cpp:117:86: error: C++ requires a type specifier for all declarations
std::array < std::array < std::array < int, radius >, image.cols >, image.rows > houghSpace;
^
【问题讨论】:
-
malloc(sizeof(int) * y * x * r);? -
如果你想要性能,方法就像第二个例子here。使用一维向量并使用数学来假装它具有多个维度。有很多方法可以做到这一点,但有些库已经这样做了,所以你应该只获得其中一种。
-
即使我像您一样采用 3 星级程序员方法,我也会将数组的整个内存分配为单个块,然后将指向该连续块的指针存储到二维数组中。
-
我会说分配 3D 数组最惯用的方法是不这样做。或者换句话说,使用平面一维数组,然后将索引映射到您喜欢的任何维度