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

0

1 Answer 1

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.

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

5 Comments

why not declaring char romFamily; directly? what's the point of 1-char array?
@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.
char romFamily[1]; is the same as char romFamily; in memory right?
@Jean-FrançoisFabre: It just might cause alignment differences in the struct on certain toolchains. Suppresses padding perhaps?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.