-1

having not worked with C for a while I'm stuck with passing a single struct from an array of structs to a function by reference.

The code I have looks like this:

struct Sensor {
    //ROM data
    char romCRC[1];
    char romSerial[6];
    char romFamily[1];
};

const int maxSens = 10;

void Read_ROM(struct Sensor *sens){
        char ROM[10];
        for (k = 0; k<8; k++){
             ROM[k] = read_byte();
             sens->romFamily = ROM[0];
        }
}

int main(){
    struct Sensor Sensors[maxSens];
    Read_ROM(&Sensors[0]);
}

What I expect it to do is:

  • Create an array of 10 structs of type Sensor
  • Pass the address of the first struct to the function Read_ROM
  • Set the member romFamily of the struct Sensor[0] to ROM[0]

read_byte is tested and working. It does return 1 char.

When I try to compile I get this error:

#138 expression must be a modifiable lvalue

With 138 being the line number of:

sens->romFamily = ROM[0];

What is wrong here?

namron
  • 75
  • 7

1 Answers1

3

Arrays are not assignable in C, although you can set individual elements.

In your case you need sens->romFamily[0] = ROM[0];

But do question why you need a single element array in the first place.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • why not declaring `char romFamily;` directly? what's the point of 1-char array? – Jean-François Fabre Nov 16 '17 at 10:09
  • @Jean-FrançoisFabre: Hard to say without the context. Might be what a "device" wants in the context of a particular toolchain, but worth indeed appending to the answer, which I've done. – Bathsheba Nov 16 '17 at 10:10
  • `char romFamily[1];` is the same as `char romFamily;` in memory right? – Jean-François Fabre Nov 16 '17 at 10:11
  • @Jean-FrançoisFabre: It just *might* cause alignment differences in the `struct` on certain toolchains. Suppresses padding perhaps? – Bathsheba Nov 16 '17 at 10:11
  • You are absolutely right. I started writing the struct with the romSerial[6] array and adapted the array notation to the other members without thinking. Simply using char romFamily; solves it. – namron Nov 16 '17 at 10:12