c - How pointer to array works? -
int s[4][2] = { {1234, 56}, {1212, 33}, {1434, 80}, {1312, 78} }; int (*p)[1]; p = s[0]; printf("%d\n", *(*(p + 0))); // 1234 printf("%d\n", *(s[0] + 0)); // 1234 printf("%u\n", p); // 1256433(address of s[0][0]) printf("%u\n", *p); // 1256433(address of s[0][0]) can explain why doing *(*(p + 0)) prints 1234, , doing *(s[0] + 0) prints 1234, when p = s[0] , why p , *p gives same result?
thanking in anticipation.
this way arrays work in c -- arrays not first class types, in can't them other declaring them , getting size. in other context, when use expression type array (of anything) silently converted pointer array's first element. referred array "decaying" pointer.
so lets @ statements 1 one:
p = s[0]; here, s has array type (it's int[4][2] -- 2d int array), silently converted pointer first element (an int (*)[2], pointing @ word containing 1234). index [0] adds 0 * sizeof(int [2]) bytes pointer, , dereferences it, giving int [2] (1d array of 2 ints). since array, silently converted pointer first element (an int * pointing @ 1234). note same pointer before index, pointed @ type different.
you assign int * p, declared int (*)[1]. since c allows assigning pointer other pointer (even if pointed @ types different), works, reasonable compiler give type mismatch warning.
p points @ word containing 1234 (the same place pointer s points at)
printf("%d\n", *(*(p+0))); this first adds 0*sizeof(int[1]) p , dereferences it, giving array (int[1]) decays pointer first element (an int * still pointing @ same place). pointer dereferenced, giving int value 1234 printed.
printf("%d\n", *(s[0]+0)); we have s[0] again via multiple decay , dereference process noted in description of first line, becomes int * pointing @ 1234. add 0*sizeof(int) it, , dereference, giving integer 1234.
printf("%u\n", p); p pointer, address of pointer printed.
printf("%u\n",*p) p dereferenced, giving int [1] (1d integer array) decays pointer first element. pointer printed.
Comments
Post a Comment