【发布时间】:2021-07-09 18:45:13
【问题描述】:
当我编译并运行以下代码时:
struct preferences {
bool likesMusic : 1;
bool hasHair : 1;
bool hasInternet : 1;
bool hasDinosaur : 1;
unsigned int numberOfChildren : 4;
};
int main() {
struct preferences homer;
homer.likesMusic = true;
homer.hasHair = false;
homer.hasInternet = true;
homer.hasDinosaur = false;
homer.numberOfChildren = 3;
printf("sizeof int: %ld bits\n", sizeof(int) * 8);
printf("sizeof homer: %ld bits\n", sizeof(homer) * 8);
printf("sizeof bool: %ld bits, sizeof unsigned int: %ld bits\n", sizeof(bool) * 8 , sizeof(unsigned int) * 8);
}
输出是:
sizeof int: 32 bits
sizeof homer: 32 bits
sizeof bool: 8, sizeof unsigned int: 32.
当我从首选项中注释掉 numberOfChildren 字段时,输出为:
sizeof int: 32 bits
sizeof homer: 8 bits
sizeof bool: 8, sizeof unsigned int: 32
这对我来说没有意义,因为 unsigned int 的大小从这个实验运行中推断为 24 位,因为在移除 numberOfChildren 字段后,homer 结构的大小从 32 位减少到 8 位。此外,输出本身包含 sizeof unsigned int: 32。
您能提供的任何见解将不胜感激。谢谢。
我的设置是 Ubuntu 20.04,64 位,英特尔架构 Xeon Silver 16 核处理器。
【问题讨论】:
-
您对结构体大小的期望究竟是什么?结果与此有何不同?
-
unsigned int 的大小被推断为 24 - 你的逻辑在两个方面存在缺陷:结构大小总是
chars 的整数(像您正在使用的主流实现上的字节),并且您没有 unsigned int 成员,您有一个 4 位 bitfield 成员,其基本类型为 unsigned int。 -
@cigen:关于该副本的答案几乎没有提到位域,但这显然是这里的关键问题,如何获得一些布尔位域和基于
unsigned int的位域到一个只有单个unsigned int大小的结构中。 How is the size of a struct with Bit Fields determined/measured? 看起来像是覆盖了它,所以仍然是重复的。
标签: c++ c struct bit-fields