0

Plz explain this c code

#include <stdio.h> int main() { int arr[3]={40,41,42}; int *ptr=(int*)(&arr+1); printf("%d %d",*(arr+1),*(ptr-1)); return 0; }

8th May 2020, 6:41 PM
Kawser
Kawser - avatar
1 Answer
+ 2
"&arr" is of type int (*)[3] "a pointer to an array of 3 ints". pointer arithmetic says adding an integer N to a pointer to an element of an array with index K produces a pointer to an element of the same array, with index K+N since “&arr” is pointer to array of 3 ints, addition of 1 resulted in an address with increment of (assuming sizeof int is 4 bytes) 4 x 3 = 12 (we end up to the addr of the next array of 3 ints if there was one ) which is decayed to int* (a pointer to an integer), subtraction of 1 resulted in an address with decrement of 4. +-----+-----+-----+-----+-----+-----+ | 40 | 41 | 42 | | | +-----+-----+-----+-----+-----+-----+ ^ ^ ^ ^ | | | | | | | | | | | | &arr | ptr-1 &arr + 1 == ptr ^ | | | arr arr + 1
8th May 2020, 7:01 PM
MO ELomari
MO ELomari - avatar