How is the size of a struct with Bit Fields determined/measured?

前端 未结 4 1997
再見小時候
再見小時候 2020-11-28 04:41
#include 

typedef struct size
{
        unsigned int a:1;
        unsigned int b:31;
        unsigned int c:1;
} mystruct;

int main()
{
        myst         


        
4条回答
  •  再見小時候
    2020-11-28 05:25

    You don't say whether you know what bitfields are, but I'll assume you do.

    On your implementation, evidently unsigned int is a 32 bit integer, occupying 4 bytes. This accounts for the first and second examples. Clearly 3 bitfields totalling 33 bits don't fit into a single unsigned int, hence the need for 8 bytes in the first example. 3 bitfields totalling 3 bits certainly do fit into an unsigned int, hence only 4 bytes in the second example.

    Furthermore, a bitfield cannot span multiple integers. This accounts for the third example. I can't remember whether that's a requirement of the standard, or just a detail of your implementation. Either way, since b is 32 bits, it fills a whole unsigned int on its own, forcing both of a and c to occupy their own unsigned int, before and after the middle one. Hence, 12 bytes.

提交回复
热议问题