I'm confused with a problem about the pointer and array in C.
Let's see a piece of code first:
//case 1
int **a;
a = (int **)malloc(sizeof(int*)*m);
for(i = 0; i < m; i++)
a[i] = (int *)malloc(sizeof(int)*n);
//case 2
int b[m][n];
then, we known that, the layout of b
in memory is as follow:
b[0][0] b[0][1] ... ... b[m-1][n-1]
and, the layout of a in memory is as follow:
a
\
_\|
a[0] a[1] ... a[m-1]
| |
| |
| \|/
| a[1][0] a[1][a] ... a[1][n-1]
\|/
a[0][1] a[0][2] ... a[0][n-1]
so, my question is: since a[0..m-1][0..n-1]
is stored in memory inconsecutively, why we can use subscript operator []
on a
? In other words, why a[i][j]
can get the correct element, just as b[i][j]
do?