I have the following to code to allocate the 3d array:
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);
}
This seems a bit clunky and it's difficult to do error-handling if I malloc fails.
That said, it's quite ergonomic because I can simply access an element like so: int a = arr[x][y][z]
What would be the best way to initialize a 3d array that gives the same ergonomic flexibility while mitigating some of the above drawbacks?
I tried this:
std::array < std::array < std::array < int, radius >, image.cols >, image.rows > houghSpace;
but I got an error:
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;
^