#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
打印从sizeof
运算符返回的size_t
。 - MikeCAT