Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the output of *(pa-1) is the last element of `a`?

Tags:

c++

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;

}
like image 984
JDein Avatar asked Dec 12 '22 23:12

JDein


1 Answers

&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.

like image 126
Kerrek SB Avatar answered Dec 14 '22 12:12

Kerrek SB