+3

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?

1/27/2020 5:35:42 PM

Sergei Romanov

4 Answers

New Answer

+4

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....

+6

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.

+4

++ptr; moves the pointer ptr on the next one memory position which is element 4 of array a. So, ptr[0] =4 and ptr[1],ptr[2]=5,6