sizeof(struct) different for different compilers

社会主义新天地 提交于 2019-11-27 08:34:41

问题


Supposing I have a code like this:

#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[]) {
    typedef struct{
        uint16_t x : 9;
        uint8_t y : 7;
    } z;
    printf("sizeof(z) = %lu\n",sizeof(z));
}

I have different results for clang on Mac (2) and someone told me on Windows it returned (3). 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?


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/28580344/sizeofstruct-different-for-different-compilers

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