I am attempting to write a procedure that lets me allocate a contiguous block of memory of size n1*n2*n3 and access it using 3 indices, like you would with an array
int array[n1][n2][n3];
I have successfully (as far as I can tell) managed this with two indices (see my example below)
#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;
}
But when I try a similar construct with three indices, my procedure throws a 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;
}
I understand there are other ways to manage a contiguous block of memory. I am specifically interested in why my logic is failing in the above case.