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?

5
  • What error message does the compiler give you? Commented Sep 12, 2018 at 20:09
  • 7
    You try to modify a const value ? Commented Sep 12, 2018 at 20:10
  • assignment of read-only location 'array[0]' Commented Sep 12, 2018 at 20:11
  • Make the members non constant for a start. Commented Sep 12, 2018 at 20:11
  • 1
    When you say "add to a struct array" are you talking about making the array bigger, or changing an existing value? That would be better written as "assign to a struct array". Commented Sep 12, 2018 at 20:17

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.