不同编译器的 sizeof(struct) 不同 [英] sizeof(struct) different for different compilers

查看:37
本文介绍了不同编译器的 sizeof(struct) 不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的代码:

#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
",sizeof(z));
}

我对 Mac 上的 clang 有不同的结果 (2),有人告诉我在 Windows 上它返回了 (3).不确定我是否理解它,但我看到当第一个编译器将结构压缩为 9+7 = 16 位时,另一个使用 16 位 uint16_t 和 8 位 uint8_t.你能给建议吗?

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?

推荐答案

不确定我是否理解它,但我看到当第一个编译器将结构压缩为 9+7 = 16 位时,另一个使用 16uint16_t 的位和 uint8_t 的 8 位.你能给建议吗?

关于位域,首先要记住的是来自 K&R, 2nd 的这句话:

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(struct) 不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆