1

I have two structs:

struct struct_A
{
  uint8_t v1[4];   // 4 bytes
  uint8_t v2;
};

struct struct_B
{
  uint32_t v1;  // 4 bytes
  uint8_t v2; // 1 byte
};

I obtain their sizes by using the code:

std::cout<<"size of struct_A is: "<<(sizeof(struct_A))    <<std::endl;
std::cout<<"size of struct_A::v1 is: "<<(sizeof(struct_A::v1))<<std::endl;
std::cout<<"size of struct_A::v2 is: "<<(sizeof(struct_A::v2))<<std::endl;
std::cout<<"size of struct_B is: "<<(sizeof(struct_B))    <<std::endl;
std::cout<<"size of struct_B::v1 is: "<<(sizeof(struct_B::v1))<<std::endl;
std::cout<<"size of struct_B::v2 is: "<<(sizeof(struct_B::v2))<<std::endl;

And I get output:

size of struct_A is: 5
size of struct_A::v1 is: 4
size of struct_A::v2 is: 1
size of struct_B is: 8
size of struct_B::v1 is: 4
size of struct_B::v2 is: 1

How do I understand the size of struct_A and size of struct_B are different? Thanks.

  • uint32_t has alignment requirement of 4, but uint8_t only needs to be aligned to 1 so `struct_B` must have 3 padding bytes to maintain alignment – phuclv May 31 '21 at 05:09

0 Answers0