+ 2

Why does the outputs be "41 and 42" for this code in C?

#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; }

12th Jun 2020, 4:19 AM
Win Htay 🇲🇲
Win Htay 🇲🇲 - avatar
6 ответов
+ 4
The first argument to printf is equivalent to arr[1] which prints the 2nd element of the array, which is 41. arr is of type int (*)[3]. So *ptr = (int *)(&arr + 1) offsets the pointer by 1 * sizeof(int) * 3 and you end up on the first block past the end of the array. But in the printf function you decrease the pointer offset by a single element *(p - 1) which gets the value of the last array element of the previous block which is 42. You can think of it as: int (*ptr)[3] = &arr; ptr++; printf("%d\n", (*ptr)[-1]); where ptr++ jumps 3 integers ahead for each increment.
12th Jun 2020, 5:50 AM
Gen2oo
Gen2oo - avatar
+ 3
*(arr+1) is easy: adding 1 to arr (which is a pointer to an int) you will point to the second element of arr[], so *(arr+1) will be equivalent to arr[1] *(ptr-1) is trickier: ptr is obtained adding 1 to &arr (not arr), which is a pointer to 3 int; this means that &arr+1 is equivalent to arr+3: it will point after the end of arr[]. If we understand this, it is easy to understand ptr-1: it is equivalent to arr+3-1, that is the last element of arr, arr[2]
12th Jun 2020, 5:56 AM
Bilbo Baggins
Bilbo Baggins - avatar
+ 2
Try: int *ptr = (int*)(arr + 1); . Your code has pointer arithmetic problem. &arr is of type int** hence the arithmetic is different from int*
12th Jun 2020, 5:43 AM
Terminal_Phantom
Terminal_Phantom - avatar
+ 2
See this code to get an idea of pointer arithmetic https://code.sololearn.com/ckTvXAXVns6m/?ref=app
12th Jun 2020, 5:48 AM
Terminal_Phantom
Terminal_Phantom - avatar
0
u added one to ur pointer address, so the behavior is undefined
12th Jun 2020, 5:49 AM
Flash