7
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?

dbush
  • 205,898
  • 23
  • 218
  • 273
Aristos Georgiou
  • 315
  • 2
  • 13

3 Answers3

10

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
5

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;
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
John
  • 577
  • 4
  • 20
4

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.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523