storing struct as an array of bytes?

Hi

I'm trying to understand some code that I saw for the Arduino here: https://playground.arduino.cc/Code/EEPROMLoadAndSaveSettings

It seems that you can create a struct with different variables and then save it to a file (or read it back). I wasn't really sure how this was working - does it save the struct as an array of bytes?

The following piece of code is what seems to be key:
1
2
3
4
  void saveConfig() {
  for (unsigned int t=0; t<sizeof(storage); t++)
    EEPROM.write(CONFIG_START + t, *((char*)&storage + t));
}


What does the following do?

 
*((char*)&storage + t)


Btw if anyone is not familiar with Arduino - EEPROM.write(x,y) just writes a byte y at pos x of the EEPROM

Thanks
> It seems that you can create a struct with different variables and then save it to a file (or read it back).

As a sequence of bytes.

Yes, if the struct is a TriviallyCopyable type.
http://en.cppreference.com/w/cpp/concept/TriviallyCopyable

If not, reading it back as a sequence of (saved) bytes would engender undefined behaviour.


> What does the following do? *((char*)&storage + t)

Accesses byte number t in the object representation of storage.
Last edited on
Thanks - so is that last bit pointer arithmetic? Please could you explain what the (char*) does?

That is a C style cast; you take a pointer to something, and then you tell the compiler to treat it as a pointer to something else.

&storage object of type pointer-to-whatever-kind-of-object-storage-is

(char*)&storage object of type pointer-to-char, pointing at the object named storage

In C++, a char is of size one byte, it's a kludgy way to access individual bytes of an object.

(char*)&storage : treat the address of storage as a pointer to char (as a pointer to the first byte in the object representation of storage).

(char*)&storage + t : the address of the byte (char) which is t bytes after the pointer (after the first byte in the object representation)

*((char*)&storage + t) : the value of that particular byte (that particular byte as an lvalue)
thanks both, much appreciated
Topic archived. No new replies allowed.