Page 1 of 1

arduino sizeof struct

Posted: Sat Feb 10, 2018 10:19 pm
by cmatooooo
I need work with struct as with struct pointer in Arduino (ESP32 in Platformio).

Code: Select all

typedef struct pokus_struct {
  unsigned char unsignedchar1;//1 byte
  float float1;          //4 bytes
} Pokus;

Pokus pokus;

  pokus.unsignedchar1=1;          
  pokus.float1=2; 

  Serial.println(sizeof(pokus)); // return to terminal 8
  Serial.write((byte*)&pokus, sizeof(pokus)); // 01 00 00 00 00 00 00 40

  Serial.println(sizeof(pokus.unsignedchar1)); // 1
  Serial.write((byte*)&pokus.unsignedchar1, sizeof(pokus.unsignedchar1)); // 01

  Serial.println(sizeof(pokus.float1)); // 4
  Serial.write((byte*)&pokus.float1, sizeof(pokus.float1)); // 00 00 00 40 
If I delete float item from struct, struct size is 1 byte, if I delete unsignedchar, struct size is 4 bytes.
I also tried define struct items with uint8_t, float_t, but it was similar (8 bytes).

Why struct size is not 5 bytes? , why it is 8 bytes?
thanks

Re: arduino sizeof struct

Posted: Sun Feb 11, 2018 4:46 am
by ESP_Sprite
It's a C-compiler / hardware optimization thing: https://en.wikipedia.org/wiki/Data_structure_alignment

Re: arduino sizeof struct

Posted: Sun Feb 11, 2018 11:53 am
by cmatooooo
I found solution:

Code: Select all

typedef struct __attribute__((packed)) pokus_struct {
  unsigned char unsignedchar1;//1 byte
  float float1;          //4 bytes
} Pokus;

Re: arduino sizeof struct

Posted: Mon Feb 12, 2018 7:01 pm
by tele_player
Unless you have good reason, and understand the implications, you should stay away from packed structs.