In C++ name of the array without a bracket, is a pointer to the first element of the array. However, I couldn't realize how the following code works
int main()
{
int x[] = {1, 2, 3, 4};
cout << "x = " << x << endl;
cout << "&x = " << &x << endl;
cout << "*(&x) = " << *(&x) << endl;
cout << "*x = " << *x << endl;
cout << "**(&x) = " << **(&x) << endl;
}
and this is the output
x = 0x7ffd179e9060
&x = 0x7ffd179e9060
*(&x) = 0x7ffd179e9060
*x = 1
**(&x) = 1
What I don't understand is
x = &x = 0x7ffd179e9060?x = &x = 0x7ffd179e9060, then must be *x = *(&x) while *x=1 and *(&x) = 0x7ffd179e9060**(&x) = 1 is working here?Thanks in advance.
Question Why are &array and array pointing to the same address?is not an answer to my question.
In C++ name of the array without a bracket, is a pointer to the first element of the array
It may seem like this, but this isn't really what is happening. The name of an array is the name of the array and denotes the array. What actually happens is that whenever you use an array-typed expression in an rvalue context, it get implicitly converted into a pointer to the array's first element.
Since most contexts are rvalue contexts, it may seem like the array is always the same as a pointer to the first element, but the details sometimes matter. In particular, the operand of a unary & is not an rvalue context, so when you say &x you get a pointer to the array as a whole. Thus x and &x end up appearing to have the same value, and the actual bit pattern of the pointer is the same; all that is different is the type.
&x, &(x) and (&x) are all the same.
As an expression, plain x is the same as &x[0]. Which is very different from &x.
&x is a pointer to the array itself, and will have the type int (*)[4]. &x[0] is a pointer to the first element of the array and will have the type int*.
The reason both &x and &x[0] points to the same location is easy to understand if we draw it:
+------+------+------+------+ | x[0] | x[1] | x[2] | x[3] | +------+------+------+------+ ^ | &x | &x[0]
As you noticed, and which can easily be seen in the drawing above, both &x and &x[0] are pointing to the same location. But they have different types.
Also, for any pointer or array p and index i, the expression p[i] is exactly equal to *(p + i). From this it's possible to deduce that *p is the same as p[0]. So *(&x) is the same as (&x)[0] which is the same as x.
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