What I got from the output of below code is *(pa-1)=5
: why so?
#include<iostream>
using namespace std;
int main(){
int a[5]={1,2,3,4,5};
int *pa=(int *)(&a+1);
cout<<"*(pa-1)="<<*(pa-1)<<endl;
}
&a
is the address of the array, and it has type "pointer-to-int[5]
". Thus &a + 1
advances by an entire array-of-five and points just past the array.
pa
is a type-punned pointer* that now treats the same address as an address inside an array of integers (not arrays!). It is thus identical to the one-past-the-end pointer a + 5
. Decrementing by one gives a pointer to the last element in the array, which is 5
.
*) This sort of type punning is acceptable and does what you expect as long as the underlying type of the array is standard-layout, which int
is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With