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;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
&ais the address of the array, and it has type “pointer-to-int[5]“. Thus&a + 1advances by an entire array-of-five and points just past the array.pais 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 pointera + 5. Decrementing by one gives a pointer to the last element in the array, which is5.*) 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
intis.