gpt4 book ai didi

C 结构的位域大小

转载 作者:行者123 更新时间:2023-12-01 03:43:11 25 4
gpt4 key购买 nike

#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。谁能解释为什么会这样?

最佳答案

对于第一个结构

struct on_off{
unsigned light : 1;
unsigned toaster : 1; // 1 byte
// 3 bytes - packing to align to int border
int count; // 4 Bytes
unsigned ac : 4;
unsigned ss : 4; // 1 Byte
unsigned clock : 1; // 1 byte
unsigned : 0; // 2 byte -- A size of zero forces alignment to next boundary.
unsigned flag : 1; // 1 byte
// 3 bytes -- Packing at end of struct to align to word boundary.
}
// 16 bytes -- Total

对于第二个结构

struct box_props{
unsigned int opaque : 1;
unsigned int fill_color : 3;
unsigned int : 4; // 1 byte
unsigned int show_border : 1;
unsigned int border_color : 3; // 1 byte
unsigned int border_style : 2;
unsigned int : 2; // 1 byte
// 1 byte - packing at the end of structure to align to word boundary.
}
// 4 bytes Total

关于C 结构的位域大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37042510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com