Here is my code:
void doubleValuesInArray(int *pointer) {
for (int n = 0; n < 2; n++) {
int a = (*pointer+n);
a = a * 2;
*pointer+n = a;
}
}
int main(int argc, char** argv) {
int myArray[] = {1,2};
doubleValuesInArray(myArray);
cout<<myArray[0]<<endl;
return 0;
}
And the output is:
main.cpp: In function `void doubleValuesInArray(int*)’:
main.cpp:19: error: non-lvalue in assignment
make[2]: * [build/Debug/Cygwin-Windows/main.o] Error 1
make[1]: [.build-conf] Error 2
make: ** [.build-impl] Error 2
My question is:
int a = (*pointer+n);
works just fine. Variable ‘a’ gets the values 0 and 1 from the array by using *pointer + n.
However
*pointer+n = a;
does not seem to work.
If I use
pointer[n] = a;
it works as well.
Why doesn’t my first approach work?
You did not parenthesize your pointer expressions correctly: the
*has higher priority, so you should add parentheses around the addition: