+ 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));
4 Antworten
+ 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.
+ 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.
0
Shadow can u explain why *(&arr+1) !=*(arr+1)
0
Shadow thanks dude