struct home
{
uint32_t calss;
uint8_t name;
float keyl;
bool flag;
uint16_t me;
};
Can someone help explain why uint8_t is padded 3 bytes but the bool is only padded a byte.
struct home
{
uint32_t calss;
uint8_t name;
float keyl;
bool flag;
uint16_t me;
};
Can someone help explain why uint8_t is padded 3 bytes but the bool is only padded a byte.
This is because float (requesting 4-byte alignment) is after uint_8 and uint16_t (requesting 2-byte alignment) is after bool in this case.
Swapping them will result in swapping the number of padding.
#include <stdio.h>
#include <stdbool.h>
#include <inttypes.h>
struct home
{
uint32_t calss;
uint8_t name;
float keyl;
bool flag;
uint16_t me;
};
struct home2
{
uint32_t calss;
uint8_t name;
uint16_t keyl;
bool flag;
float me;
};
int main(void) {
struct home h;
struct home2 h2;
printf("home:\n");
printf("calss : %p\n", (void*)&h.calss);
printf("name : %p\n", (void*)&h.name);
printf("keyl : %p\n", (void*)&h.keyl);
printf("flag : %p\n", (void*)&h.flag);
printf("me : %p\n", (void*)&h.me);
printf("home2:\n");
printf("calss : %p\n", (void*)&h2.calss);
printf("name : %p\n", (void*)&h2.name);
printf("keyl : %p\n", (void*)&h2.keyl);
printf("flag : %p\n", (void*)&h2.flag);
printf("me : %p\n", (void*)&h2.me);
return 0;
}
home:
calss : 0x7ffcd0f9b4a0
name : 0x7ffcd0f9b4a4
keyl : 0x7ffcd0f9b4a8
flag : 0x7ffcd0f9b4ac
me : 0x7ffcd0f9b4ae
home2:
calss : 0x7ffcd0f9b490
name : 0x7ffcd0f9b494
keyl : 0x7ffcd0f9b496
flag : 0x7ffcd0f9b498
me : 0x7ffcd0f9b49c
The first field is padded 3 bytes because the next field (a float) requires four byte alignment, and so, three bytes are needed to align it to a multiple of four bytes. The second field (the bool) has one byte of padding for the same reason: the next field (an uint16_t, 16 bit wide) requires 2 byte alignment, and so only one byte is needed to get a 2 byte alignment.
For the final padding, you compute the struct alignment as the largest alignment of the largest field in the structure, and padding is included to make an array of such structs correctly aligned. The structure's sizeof will reflect this final alignment, so an array of such structures will have all cells aligned with just aligning the first one.
If you reorder the struct fields making the two one byte fields to be together and before or after the 2 byte data, then you'll get a structure with no gaps. This is because after the one field aligned field there's another one byte field, and the next field (the two bytes field) is already aligned to a multiple of 2 address, so no padding is necessary. After the 2 bytes field, the alignment is already 4 bytes aligned, so the next field will be immediately after.