Consider the following code. I’ve included excessive couts for clarity (at least on my end):
#include <iostream>
using namespace std;
int main(){
double *array1;
array1 = new double[10];
array1[5] = 10;
//the following 2 lines return the same thing
cout << "array1 = " << array1 << endl;
cout << "&array1[0] = " << &array1[0] << endl;
double *subarray1;
subarray1 = new double[5];
subarray1 = &array1[5];
//now the following 2 lines return the same thing
cout << array1[5] << endl;
cout << subarray1[0] << endl;
//but I'm not allowed to do:
//&subarray1[0] = &array1[5];
return 0;
}
since
subarray1 == &subarray1[0]
and since I am allowed to do this:
subarray1 = &array1[5];
then why can’t I do this:
&subarray1[0] = &array1[5];
The error that I receive is: warning: target of assignment not really an lvalue; this will be a hard error in the future
The expression
subarray1is an lvalue to your pointer object of the same name. This pointer points to the first element of the dynamically-allocated buffer.The expression
&subarray1[0]is an rvalue pointer that points to the first element of the dynamically-allocated buffer (and thus it evaluates to the same value assubarray1).These are not the same thing, and you may not assign to an rvalue.