Offset in a struct with bit fields

久未见 提交于 2019-12-03 17:06:57

how are the subsequent members aligned in the struct?

Nobody knows. This is implementation-defined behavior and thus compiler-specific.

What is happening in the 2nd case?

The compiler may have added padding bytes or padding bits. Or the bit order of the struct might be different than you expect. The first item of the struct is not necessarily containing the MSB.

What is the rule for padding in structs involving bit fields in general?

The compiler is free to add any kind of padding bytes (and padding bits in a bit field), anywhere in the struct, as long as it isn't done at the very beginning of the struct.

Bit-fields are very poorly defined by the standard. They are essentially useless for anything else but chunks of boolean flags allocated at random places in memory. I would advise you to use bit-wise operators on plain integers instead. Then you get 100% deterministic, portable code.

I would take a small example. Hope this will make clear :: Consider two structures :

struct {
    char a;
    int b;
    char c;
} X;

Versus.

struct {
    char a;
    char b;
    int c;
} Y;

A little more explanation regarding comments below:

All the below is not a 100%, but the common way the structs will be constructed in 32 bits system where int is 32 bits:

Struct X:

|     |     |     |     |     |     |     |     |     |     |     |     |
 char  pad    pad   pad   ---------int---------- char   pad   pad   pad   = 12 bytes

struct Y:

|     |     |     |     |     |     |     |     |
 char  char  pad   pad   ---------int----------        = 8 bytes

Thank you

Some reference ::

Data structure Alignment-wikipedia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!