Pointers to pointers are not the same as "straight" multidimentional arrays. They operate very, very differently under the hood and cannot be used interchangably.
You are creating a 1D array (int*) and casting it to a 3D array (int***) which will fail horribly because the compiler will be treating the ints in the array as if they were pointers, and dereferencing memory which does not exist.
Multidimentional dynamic memory is a pain, which is one of the reasons why I avoid it. If you want to do it you'll need to do one of 2 things:
1) Use a 1D array and simulate the other 2 dimensions with calculations:
1 2 3 4 5 6 7
|
int* array = malloc(sizeof(int) * width * height * depth);
// to get x,y,z:
array[ ((z * height) + y) * width + x ] = 5;
// cleanup
free(array);
|
or 2) allocate each dimension separately (use the pointer to pointer to pointer approach):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
int*** array = malloc(sizeof(int**) * depth);
for(int i = 0; i < depth; ++i)
{
array[i] = malloc(sizeof(int*) * height);
for(int j = 0; j < height; ++j)
array[i][j] = malloc(sizeof(int) * width);
}
// to get x,y,z
array[z][y][x] = 5;
// cleanup:
for(int i = 0; i < depth; ++i)
{
for(int j = 0; j < height; ++j)
free(array[i][j]);
free(array[i]);
}
free(array);
|
As you can see, both approaches are very ugly.
In C++ either approach can be wrapped in a class to make it less error prone and easier to use. Since you seem to be using C, you can do the same thing with structs.