arrays and pointer arithmetic ~ clarification needed
Because the precedence of the operator []
is higher than the operator *
, the following expression:
int x = *(a + i)[j];
is equal to:
int* p = (a + i)[j];int x = *p;
which is also equal to:
int* p = ((a + i) + j);int x = *p;
which in this case is equal to:
int (*p0)[3] = (a + i);int* p = (p0 + j);int x = *p;
meaning that both i
and j
eventually shift the first index making p
to point to element a[2][0]
, value of which is 7
And what has precedence of []
and *
operators to do with the evaluation of this expression? Simple test by using ()
to make sure that *
will be evaluated first will suffice here. Meaning that this:
int y = (*(a + i))[j];
is equal to:
int y = *(a[i] + j);
which is nothing but simple:
int y = a[i][j];
Lets say a+i
is b
+--------------a+0---> {1, 2, 3, | a+1---> 4, 5, 6, | a+2---> 7, 8, 9}; |*(a + i)[j] = *(*(b+j)) = *(*(b+1)+1) = *(*(b+2)) = *(*(a+2)) = **(a+2) = a[2][0] = 7
int (*p)[3]; // Is pointer to array of 3 int s
When p=a
same scenario , similar to using b