+ 7

Please explain!

How the output is 3 ? int arr[]={1,2,3}; int *p=(int *)(&arr + 1); printf("%d",*(p-1)); https://code.sololearn.com/cYANoAqimJYM/?ref=app

29th Jan 2021, 4:25 AM
Hrutik Bhalerao
Hrutik Bhalerao - avatar
3 Antworten
+ 9
&arr is a pointer to the array (int(*)[3]). arr decays to a pointer to the first element of the array (int*). Both &arr and arr point to the same address, but their types differ so pointer arithmetic is performed differently. If instead you wrote arr + 1, you would have been correct. When you perform pointer arithmetic p + n, you get a pointer that is moved n times the size of the type pointed to (sizeof(*p)). The type pointed to by &arr is int[3] which is 12 bytes. &arr + 1 then points to a int[3] after the end of the array. (int*)(&arr + 1) == arr + 3 (int *)(&arr + 1) converts the pointer to array (12 bytes) to pointer to int (4 bytes). p is then pointing to an int after the end of the array. p - 1 gives you a pointer to the last element of the array which is 3. int* p = arr + 3; printf("%d", *(p - 1)); // *(arr + 3 - 1) == *(arr + 2) == arr[2]
29th Jan 2021, 5:13 AM
jtrh
jtrh - avatar
0
int *p=(int *)(arr + 1); I think this will help you to find you answer.
30th Jan 2021, 11:27 PM
❤️😍Prerana😍❤️
❤️😍Prerana😍❤️ - avatar
- 2
Try this and u can answer by yourself. int *p=(int *)(arr + 1);
30th Jan 2021, 6:54 AM
SERG Starkov
SERG Starkov - avatar