+ 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?
2 Antworten
+ 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.