mercredi 5 mai 2021

Smallest sizeof of bit field

I have some problems with understanding results returned by sizeof.

Let assume that I have two structs:

typedef struct{
    unsigned int  age    : 4;
    unsigned char gender : 1;
    unsigned int  size   : 2;
} child_t;

typedef struct{
    unsigned int  age    : 4;
    unsigned char gender : 1;
    unsigned int  size   : 2;
} __attribute__((packed)) child_t_packed;

https://coliru.stacked-crooked.com/view?id=10866c66fe82f4e4

Could you explain why the size of the first struct is 4 bytes?

Probably I am wrong, but I expected 2 bytes. (4 bits in the first row and 3 bits in the second row).

The packed version ignores alignment and in the second case sizeof(child_t_packed) = 1 byte. Does it mean that 1 byte is the smallest size a variable of the type child_t_packed may occupy in memory? or the smallest value could be 7 bits?

Aucun commentaire:

Enregistrer un commentaire