Struct on EEPROM

When I use EEPROM.put() to write a struct on the EEPROM, are the fields stored in the order they are declared in the struct? For example, if my first field in the struct is a char array with size 10, are the first 10 bytes from the location I started writing occupied with the contents of that array? Or it isn't guaranteed?

From the looks of it, a struct is converted to a byte array that is written to the EEPROM. So the order should be the same as in memory.

1 Like

Why incidentally does it matter to you ? You'll probably be using EEPROM.get() to recover the data from EEPROM into the same struct. Or are you doing something unusual with it ?

The struct represents a profile with username, password etc. and I want to get the username. But for getting the username, I think I need to know at what location it starts, right?

Wrong

Just get() the struct from EEPROM and you have the username

1 Like

Oh, yeah, I get it now. I read the examples wrong. Thanks!

Right! You need to know the numerical value of the location and enter it in the get() method.

See the following sketch;

#include<EEPROM.h>

struct myData
{
  char myName[10];
  int passW;
};

myData data;

struct rdData
{
  char myName[10];
  int passW;
};

rdData proRd;

void setup()
{
  Serial.begin(9600);
  memcpy(&data.myName, "Golam", sizeof data.myName);
  data.passW = 1234;
  EEPROM.put(0x0100, data);  //storing struct into EEPROM
  EEPROM.get(0x0100, proRd); //retrieving the struct from EEPROM
  Serial.println(proRd.myName); //shows: Golam
}

void loop()
{

}

When you use the struct:

  • the members of the struct (the order) is maintained

  • but there can be "alignment gaps": for instance: after a char - a long follows as a struct member: the long starts always at an even, potentially the next address dividable by 4 (32bit aligned), so there is a gap between char and long (3 bytes for alignment)

  • it is possible to define structs as "packed": then you do not have the gaps. But the larger types, as long - are not properly aligned anymore.

In your example: between myName[10] and passW; can be a gap of two bytes: the myName ends on address offset 10, but for the int you might need to have it started at 12 (4 byte aligned).

Just print the "sizeof(struct myData)" and you will see the effect.

1. The compiler likes sizeof(data) and not sizeof(struct myData).
2. The command Serial.print(sizeof(data)); shows 12 which means there is no location gap; the memory allocation is contiguous. (In Arduino UNO an int is 2-byte).

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.