的sizeof(结构)对于不同的编译器不同 [英] sizeof(struct) different for different compilers
问题描述
假如我有一个code是这样的:
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));
}
我对Mac上的铿锵不同的结果(2),有人告诉我,在Windows上,它返回(3)。不知道如果我理解得很好,但我看到,虽然第一个编译器COM presses的结构,以9 + 7 = 16位,另一个使用uint16_t 16位,uint8_t有8个。你能指教?
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?
推荐答案
的不知道如果我理解得很好,但我看到的是,虽然第一个编译器COM presses的结构,以9 + 7 = 16位,另一种使用uint16_t的16位和uint8_t有8。你能指教?的
要记住位字段的第一件事就是从K&放这句话; R,2日:
The first thing to remember about bit-field is this phrase from K&R, 2nd:
(6.9位域)几乎一切有关领域,是实现相关的。
(6.9 Bit-fields) "Almost everything about fields is implementation-dependent."
它包括填充,对齐和字节序位
It includes padding, alignment and bit endianness.
这篇关于的sizeof(结构)对于不同的编译器不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!