sizeof(struct) different for different compilers

╄→尐↘猪︶ㄣ 提交于 2019-11-28 14:20:57

Not sure if I understand it well, but I see that while first compiler compresses the struct to 9+7 = 16 bits, the other uses 16 bits of uint16_t and 8 of uint8_t. Could you advise?

The first thing to remember about bit-field is this phrase from K&R, 2nd:

(6.9 Bit-fields) "Almost everything about fields is implementation-dependent."

It includes padding, alignment and bit endianness.

There are two possible problems that might be occurring:

Bit-fields are very poorly standardized part within the ANSI C specification. The compiler chooses how bits are allocated within the bit-field container.You should avoid using them inside structures instead you can use #define or enum.

The second possible issue is that the compiler will lay the structure in memory by adding padding to ensure that the next object is aligned to the size of that object.It is a good practices to place elements of the struct according to their size:

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