Is it true that C++ array is a const pointer in C++ ?
http://www.cplusplus.com/forum/articles/10/#msg1381
So why is x and &x the same if they are pointers?
#include<iostream>
using namespace std;
int main() {
int x[5];
int *y = new int[5];
cout << "&x : " << &x << endl;
cout << "x : " << x << endl;
cout << endl;
cout << "&y : " << &y << endl;
cout << "y : " << y << endl;
return 0;
}
Output:
&x: 0xbfec4ccc
x : 0xbfec4ccc
&y: 0xbfec4ce0
y : 0x8961008
Link to ideone of above code:
http://ideone.com/3JRZd
No, it is not true that an array is a const pointer in C++. Indeed if one file contains
and the other contains
in the same scope, combining both files will cause strange errors.
However, arrays decay into pointers in most situations. More exactly, if you use an array in an rvalue context, it is implicitly converted into a pointer to its first element. This is what happens to x in the example in the second link: Since the first element of the array of course is at the same address as the array, both
xand&xare printed as the same address. However note that they are not the same pointer because they are of different types:xin this context decays intoint*, i.e. pointer toint, while&xis of typeint(*)[5], i.e. pointer to array of 5ints.Another case where you can see that both are different is a function taking a reference to an array, like
You can pass
xto this function (because it is of typeint[5]) but neither&xnor the pointeryyou get when writingint* y = x;