I know about algorithms to allocate/deallocate a 2D array dynamically, however I\'m not too sure about the same for 3D arrays.
Using this knowledge and a bit of symmetry
This is a version of the idea in the question but using only one malloc, inspired by the other answers. It allows intuitive use of the square brackets and easy cleaning. I hope it does not make any compiler implementation specific assumption.
int main(int argc, char *argv[])
{
int **array, i, j;
array = allocate2d(3, 4);
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
array[i][j] = j + i + 1;
}
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
printf("array[%d][%d] = %d\n", i, j, array[i][j]);
}
}
free(array);
return EXIT_SUCCESS;
}
int **allocate2d(int x, int y)
{
int i;
int **array = malloc(sizeof(int *) * x + sizeof(int) * x * y);
for (i = 0; i < x; i++)
{
array[i] = ((int *)(array + x)) + y * i;
}
return array;
}