+ 6
C challenge quiz
Can anyone explain me this code? int a[][3] = {1, 2, 3, 4, 5, 6}; int (*ptr)[3] = a; printf("%d %d ", (*ptr)[1], (*ptr)[2]); ++ptr; printf("%d %d", (*ptr)[1], (*ptr)[2]); Why does it not print "2 3 4 5" and prints "2 3 5 6" instead?
3 odpowiedzi
+ 6
Sergei Romanov
Some more information to add in previous answer.
int (*ptr)[3] = a; // here ptr is pointer to an array of 3 integers.
At first ptr is pointing to first row. Say address of 1st row is 8000
So,
(*ptr)[1]=*(8004)=2 and
(*ptr)[2]=*(8008)=3
Now ++ptr is updating pointer to next row. So, Now ptr pointing to address 8000+3*4=8012
So, Now So,
(*ptr)[1]=*(8016)=5 and
(*ptr)[2]=*(8020)=6
This way pointer is moving in above code snippet....
+ 7
blackwinter DishaAhuja thank you very much. Is "int a[][3] = {1, 2, 3, 4, 5, 6}" considered as "int a[][3] = {{1, 2, 3}, {4, 5, 6}}? I.e. I just had no idea where ptr would point to after ++ptr.
0
ptr it's point to first 3 element in array in 4th line when you encreased ptr = ptr + 1 ; ptr will pointed to next 3rd elements in array without this line the output will be 2 3 2 3 the ptr will pointed for (3 int) togather in this line (++ptr == ptr = ptr + 1 ) will increased 3*4 address in memory