arduino sizeof struct

cmatooooo
Posts: 2
Joined: Sat Feb 10, 2018 10:02 pm

arduino sizeof struct

Postby cmatooooo » Sat Feb 10, 2018 10:19 pm

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

ESP_Sprite
Posts: 9715
Joined: Thu Nov 26, 2015 4:08 am

Re: arduino sizeof struct

Postby ESP_Sprite » Sun Feb 11, 2018 4:46 am

It's a C-compiler / hardware optimization thing: https://en.wikipedia.org/wiki/Data_structure_alignment

cmatooooo
Posts: 2
Joined: Sat Feb 10, 2018 10:02 pm

Re: arduino sizeof struct

Postby cmatooooo » Sun Feb 11, 2018 11:53 am

I found solution:

Code: Select all

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

tele_player
Posts: 90
Joined: Sun Jul 02, 2017 3:38 am

Re: arduino sizeof struct

Postby tele_player » Mon Feb 12, 2018 7:01 pm

Unless you have good reason, and understand the implications, you should stay away from packed structs.

Who is online

Users browsing this forum: Baidu [Spider] and 71 guests