Two dimensional array
I am just interested in the following sample, how compiler maps one dimensional int pointer array to two dimensional int array so perfect. E.g. p  maps to the 33th element and p  maps to the 9th element.
How does the compiler do the internal mapping of one dimensional int pointer array (variable p) and the two dimensional int array (variable buffer)?
int main (int argc, char** argv)
int (*p) ;
int buffer ;
int i = 0;
int j = 0;
// to initialize
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
buffer [i][j] = i * 10 + j;
p = &buffer;
tmp = p ; // tmp = 33
tmp = p ; // tmp = 9
thanks in advance,
First off, it should be p = buffer; (no & needed here).
Second, your pointer isn't a 1-D pointer as such, it is a pointer to an ARRAY of 10 integers.
int (*p)  and int *p might look superficially to be similar, but they're really quite different. The parentheses are really important to figuring out what is going on.
int (*p)  - p is a pointer to an array of 10 ints.
int *p - p is an array of 10 pointers to int.
> How does the compiler do the internal mapping of one dimensional int pointer array
> (variable p) and the two dimensional int array (variable buffer)?
Because p is the same as your array (in essence in this context). If you were to pass buffer to a function, then it's type would be the same as p.
For the array, the elemsPerRow is obvious from the declaration, so
arr[row][col] performs array + row * elemsPerRow + col
Because the pointer type also contains the 'elemsPerRow' encoded into the type itself, the compiler is also able to deduce that
p[row][col] performs p + row * elemsPerRow + col
Basically, the same calculation gives the same answer.
> int buffer ;
Imagine this as int (buffer );, where the inner part tells us that buffer is an array of 10 'somethings'. The something in this particular case is an array of 10 ints.
I think in my code, I can change int (*p)  to int* p, and leave other code unchanged and the effect of the program should be the same, right?
Originally Posted by Salem
> I can change int (*p)  to int* p, and leave other code
> unchanged and the effect of the program should be the same, right?
No, it wouldn't work at all.
For a start, you'd lose the two dimension subscripting of your p variable later on.