【发布时间】:2016-08-30 18:20:09
【问题描述】:
#include <stdio.h>
int main() {
struct on_off {
unsigned light : 1;
unsigned toaster : 1;
int count;/* 4 bytes */
unsigned ac : 4;
unsigned : 4;
unsigned clock : 1;
unsigned : 0;
unsigned flag : 1;
} kitchen;
struct box_props {
unsigned int opaque : 1;
unsigned int fill_color : 3;
unsigned int : 4;
unsigned int show_border : 1;
unsigned int border_color : 3;
unsigned int border_style : 2;
unsigned int : 2;
} s;
printf("\n\nSize of struct on_off = %d\n", sizeof(struct on_off));
printf("\nSize of box_props = %d\n", sizeof(struct box_props));
return 0;
}
在编译此程序时,struct on_off 的大小报告给16,而box_props 的大小报告给4。谁能解释一下为什么会这样?
【问题讨论】:
-
可能是因为它易于对齐?顺便说一句,您通过将类型错误的数据传递给
printf()来调用未定义的行为。%zu,而不是%d,应该用于打印size_t,它是从sizeof运算符返回的。
标签: c