address of pointer to C multi-dimension array -
question code below:
#include <stdio.h> int main(int argc,char *arg[]){ if (argc>2){ int m=atoi(arg[1]); int n=atoi(arg[2]); int a[m][n]; int (*p)[m][n]=&a; printf("p : %p, *p : %p, **p : %p\n",p,*p,**p); } return 0; }
main env: gcc version 4.6.3 (ubuntu/linaro 4.6.3-1ubuntu5) x86-64
gcc main.c ./a.out 2 4
output:
p : 0xbfea7ef0, *p : 0xbfea7ef0, **p : 0xbfea7ef0
question why p == *p == **p
. think may because a
array, kind of constant pointer address specific, , involves implementation detail of gcc.
the observed behaviour same fixed-size arrays , variably-modified arrays:
#include <stdio.h> int main(void) { enum { m = 3, n = 4 }; int a[m][n]; int (*p)[m][n] = &a; printf("p : %p, *p : %p, **p : %p\n", p, *p, **p); return(0); }
on machine, produced:
p : 0x7fff6c542520, *p : 0x7fff6c542520, **p : 0x7fff6c542520
of course, p
pointer 2d array in both programs (and shan't add 'in both programs' qualifier again, though applies). when print p
, address of array that's assigned it, address of a
. because p
pointer 2d array, *p
'is' 2d array, array reference becomes pointer first element in situations, *p
pointer a[0]
, same memory location a
references. similarly, **p
'is' 1d array, similarly, **p
pointer a[0][0]
, same memory location a
references. so, 3 values supposed same, , compiler gets right.
that's not easy reading, then, neither c trying explain.
here's minor variation on original program illustrates sizes of different objects pointed @ p
, *p
, **p
:
#include <stdio.h> int main(void) { enum { m = 3, n = 4 }; int a[m][n]; int (*p)[m][n]=&a; printf("p+0 : %p, (*p)+0 : %p, (**p) + 0 : %p\n", (void *)(p+0), (void *)((*p)+0), (void *)((**p)+0)); printf("p+1 : %p, (*p)+1 : %p, (**p) + 1 : %p\n", (void *)(p+1), (void *)((*p)+1), (void *)((**p)+1)); return(0); }
strictly, %p
conversion specification should given void *
; casts here enforce that. original code is, officially, bit sloppy, though there few machines matter.
the output was:
p+0 : 0x7fff63453520, (*p)+0 : 0x7fff63453520, (**p) + 0 : 0x7fff63453520 p+1 : 0x7fff63453550, (*p)+1 : 0x7fff63453530, (**p) + 1 : 0x7fff63453524
note how sizes of objects pointed @ different, represented +1
version:
sizeof(*p) = 0x30 sizeof(**p) = 0x10 sizeof(***p) = 0x04
Comments
Post a Comment