+ 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?

27th Jan 2020, 5:35 PM
SergeiRom
3 Answers
+ 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....
27th Jan 2020, 6:09 PM
DishaAhuja
DishaAhuja - avatar
+ 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.
27th Jan 2020, 7:29 PM
SergeiRom
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
18th Nov 2024, 11:33 AM
Mohammed obaida Hamzah