Reputation: 315
typedef struct Expected {
const int number;
const char operand;
} Expected;
Expected array[1];
Expected e = {1, 'c'};
array[0] = e;
I don't understand why you cannot add to a struct array like that. Do I have to calculate the positions in memory myself?
Upvotes: 7
Views: 216
Reputation: 579
Making the struct members const
means you can't write to them.
After removing that it works.
typedef struct Expected {
int number;
char operand;
} Expected;
Upvotes: 5
Reputation: 727047
This is not allowed because struct
has const
members:
error: assignment of read-only location
array[0]
array[0] = e;
When a struct
has one const
member, the whole struct
cannot be assigned as well.
If it were possible to assign array elements like that, one would be able to circumvent const-ness of any member of a struct
like this:
Expected replacement = {.number = array[0].number, .operand = newOperand}; // << Allowed
array[0] = replacement; // <<== This is not allowed
Compiler flags this assignment as an error (demo).
If you need to keep const
, you would have to construct your array with initializers instead of using assignments.
Upvotes: 4
Reputation: 225352
The element of Expected
are declared const
. That means they can't be modified.
In order to set the values, you need to initialize them at the time the variable is defined:
Expected array[1] = { {1, 'c'} };
The fact that you're using an array doesn't matter in this case.
Upvotes: 10