Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C array of struct

Tags:

c

struct

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?

like image 781
Aristos Georgiou Avatar asked Sep 12 '18 20:09

Aristos Georgiou


2 Answers

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.

like image 141
dbush Avatar answered Sep 27 '22 15:09

dbush


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;
like image 30
John Avatar answered Sep 27 '22 17:09

John