I don't understand what is happening internaly.I know. * (arr+1) means arr[1]=41, but don't understand with ptr. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I don't understand what is happening internaly.I know. * (arr+1) means arr[1]=41, but don't understand with ptr.

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

15th Jul 2021, 4:59 PM
DEBANJAN GHOSH
DEBANJAN GHOSH - avatar
4 Answers
+ 2
&arr + 1 is a pointer past the end of the array. You are not allowed to dereference it, otherwise you run into undefined behaviour. In the latter expression, "arr" decays into a pointer to the first element, so it just returns the second element. The difference is that &arr explicitly forces the creation of a pointer to an integer array, whereas the implicit conversion is a decay to a pointer to an integer. As such, the size of the pointed-to type is different, and pointer arithmetic is not the same for both pointers.
15th Jul 2021, 6:56 PM
Shadow
Shadow - avatar
+ 1
&arr returns a pointer to the type of its operand. Since "arr" is an array, its type is int[ 3 ], and because pointer arithmetic is done in terms of the size of the pointed-to object, &arr + 1 returns a pointer past the end of the array (you start at the first element and move forward by the number of elements in the array). Through casting we then obtain a pointer to an integer, so when we move backwards by one in the expression *( ptr - 1 ), we do so only by one integer element, and end up at the adress of 42.
15th Jul 2021, 6:28 PM
Shadow
Shadow - avatar
0
Shadow can u explain why *(&arr+1) !=*(arr+1)
15th Jul 2021, 6:47 PM
DEBANJAN GHOSH
DEBANJAN GHOSH - avatar
0
Shadow thanks dude
15th Jul 2021, 7:03 PM
DEBANJAN GHOSH
DEBANJAN GHOSH - avatar