0

Output question pointers

int arr[3]={40,41,42}; int *ptr=(int*)(&arr+1); printf("%d %d", *(arr+1), *(ptr-1)); Why is the answer 41,42?

23rd Jan 2021, 1:29 PM
Achintya Raj
Achintya Raj - avatar
1 Resposta
+ 6
Writing *(arr+i) is same as writing arr[i]. So *(arr+1) = arr[1] = 41. (1st answer) (Since in C array index starts from 0.) &arr is address of the whole array arr[]. When we add 1 to &arr, we get base address of arr[] + sizeof(arr). And then this value is typecasted to int *. So ptr points to the memory just after 42 is stored. Then you're type-casting ptr to int * and printing the value of *(ptr-1). Since ptr points memory after 42, ptr - 1 points to 42. (2nd answer)
23rd Jan 2021, 2:01 PM
Minho
Minho - avatar