Reputation: 163
In the below code-
(Consider this codes is enclosed in the main function with all the necessary headers)
int arr[5] = {10,20,30,40,50};
cout << &(arr);
cout << &(arr+1);
If we just keep the first cout it works and prints the starting address of the array.
But if we keep the second cout it gives compilation error.
Why does it behaves in this manner?
Upvotes: 2
Views: 619
Reputation: 238341
Why does it behaves in this manner?
Adding an integer to a pointer† is an expression that results in a new value. The value category of the expression is rvalue.
The operand of the address-of operator must be an lvalue. Rvalues are not lvalues. You cannot take the address of an expression that returns a new value.
It is somewhat unclear what you're trying to do. Here are some examples of expressions:
&(arr[0]) // address of the first element
arr + 0 // same as above
&(arr[1]) // address of the second element
arr + 1 // same as above
&arr // address of the array.
// note that type of the expression is different,
// although the value is same as the first element
(&arr) + 1 // address of the next array (only valid if arr is
// a subarray within a multidimensional array
// which is not the case in your example)
&(arr+1) // ill-formed; has no sensical interpretation
† arr
is not a pointer; it is an array. But arrays decay to a pointer to first element in expressions that use the value, so in this context the type of the expression is indeed a pointer after the array-pointer conversion.
Upvotes: 1
Reputation: 73376
Because &
is taking the address of an lvalue, i.e. an object.
arr
is an lvalue that corresponds to the array. This is why the first works. But arr+1
isn't. It's a temporary result (which by the way corresponds already to an address).
If you want to get the address, without compilation error, you can use one of the following:
cout << arr+1 <<endl; // get address directly using pointer maths
cout << &arr[1] <<endl; // gets address of an element in the array
cout << &*(arr+1) <<endl; // long and painful: transform an address in a pointr
// and back again. Better use the first alternative
Here an online demo. By the way, the first can be simplified to cout<<arr<<endl;
Upvotes: 1