c++ why struct with uint32_t and struct with uint8_t[4] have different sizes?

44 views Asked by At

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.

0

There are 0 answers