Multidimensional arrays can be built dynamically using pointers to pointers with malloc. In the example below, pointer-to-pointer-to-int is declared. After the declaration, the pointer does not matter. Then a call to mallac asks that the pointer points to a block of nx valid memory blocks:
x = (int **) malloc(nx * sizeof(int *));
After this call, x now has a valid value; in particular, the starting address of a memory block that contains nx pointers to international. Each of these pointers to int is a regular pointer, as we have seen many times. They are not yet initialized to any significant, and each of them can be accessed as either
x[0], x[1] ... x[nx-1], OR *x, *(x+1), *(x+2), ... *(x+nx-1).
To give each of these pointers a meaningful value, we can call malloc for each of them, for example, this loop:
for (i=0;i<nx;++i){ x[i] = ( int * ) malloc( ny * sizeof(int)); }
Please note that we could also say:
for (i=0;i<nx;++i){ *(x+i) = ( int * ) malloc( ny * sizeof(int)); }
Now that every pointer in our array of pointers points to a significant block of memory (each of the sizes is ny ints), we can assign values. To understand how values ββare assigned, consider the diagram below. You will need to study this very carefully, while it is very clear what is happening. It may be a little complicated, but once you get it, it is not so bad.
x[0] ---> | *x[0] | *x[0]+1 | *x[0] + 2 | ... | *x[0]+ny-1 | x[1] ---> | *x[1] | *x[1]+1 | *x[1] + 2 | ... | *x[1]+ny-1 | . . . x[nx-1] ---> | *x[nx-1] | *x[nx-1]+1 | *x[nx-1] + 2 | ... | *x[nx-1]+ny-1 |
This is equivalent to:
x[0] ---> | *(*(x+0)+0) | *(*(x+0)+1) | *(*(x+0)+2) | ... | *(*(x+0)+ny-1) | x[1] ---> | *(*(x+1)+0) | *(*(x+1)+1) | *(*(x+1)+2) | ... | *(*(x+1)+ny-1) | . . . x[nx-1] ---> | *(*(x+nx-1)+0) | *(*(x+nx-1)+1) | *(*(x+nx-1)+2) | ... | *(*(x+nx-1)+ny-1) |
And this is equivalent to:
x[0] ---> | x[0][0] | x[0][1] | x[0][2] | ... | x[0][ny-1] | x[1] ---> | x[1][0] | x[1][1] | x[1][2] | ... | x[1][ny-1] | . . . x[nx-1] ---> | x[nx-1][0] | x[nx-1][1] | x[nx-1][2] | ... | x[nx-1][ny-1] |
... given the important ratio:
*( *(x + i) + j) = *( x[i] + j) = x[i][j]