Home > Software design >  "expression is not assignable" when trying to assign a value to an element of an array of
"expression is not assignable" when trying to assign a value to an element of an array of

Time:11-24

I created the following:

//main.cpp

const int size = 3;

int field[size][size] = {{0}};
int (*pfield)[size] = field;

A class of mine wants to set a value within a function:

//userInputs.cpp

int UserInputs::setValue(int (*field)[3], int x, int y) {

...


((*field)[x]   y) = value;

...

}

And it causes the following error:

src/userInputs.cpp:15:26: error: expression is not assignable
                        ((*field)[x]   y) = value;

As far as my understanding goes should ((*field)[x] y) = value; give me access to the to the value. Obviously, that's not the case and my issue is me not really understanding what went wrong. Not really experienced in C and pointers.

I appreciate any answers and/or explanations.

CodePudding user response:

If you break down ((*field)[x]) y you can see why it's unassignable.

C expressions are roughly read inside out so we start with (*field), which is the same as field[0], then tack on [x] and you have field[0][x], which is still an l-value (assignable, i.e., can be on the left hand side of an =). Then tack on the y and you have field[0][x] y, which is now y added to the value at field[0][x] so is now an r-value (not assignable).

If you want to fix it and keep the form roughly the same, the * needs to move out of the (()). That is, *(field[x] y) = value; Or more simply as field[x][y] = value;

  • Related