#include <stdio.h>
/*
*结构体中允许存在位段、无名字段以及字对齐所需的填充字段。
*位段的类型必须是int, unsigned int或signed int(或加上限定符)。
*至于int位段的值可不可以取负值取决于编译器。
*在使用位段时,要考虑字对齐的问题。系统默认的是4字节对齐。
*
*/
//4Bytes
struct S1
{
unsigned int inactive : 1;// 分配1个bit
};
//4Bytes
struct S2
{
unsigned int inactive : 1;// 分配1个bit
short id; // 与inactive共用4个Bytes
};
//2Bytes
struct S3
{
short id;
};
//4Bytes
struct S4
{
unsigned int inactive : 1;// 分配1个bit
short id; // 与inactive共用4个Bytes
unsigned int : 0;// 填充到下一个字边界
};
//8Bytes
struct S5
{
unsigned int inactive : 1;// 分配1个bit
unsigned int : 0;// 填充到下一个字边界
short id; // 占用下1个新的4个Bytes(字对齐)
};
//8Bytes
struct S6
{
unsigned int inactive : 1;// 分配1个bit
unsigned int : 0;// 填充到下一个字边界
unsigned int new_Bytes : 1;// 占用新的4个Bytes
unsigned int new_Bytes1 : 1;// 与new_Bytes共用1个Bytes
short id; // 与new_BYtes,new_Bytes1共用1个Bytes
};
//12Bytes
struct S7
{
unsigned int inactive : 1;// 分配1个bit
unsigned int : 0;// 填充到下一个字边界
unsigned int new_Bytes : 1;// 占用新的4个Bytes
short id; // 与new_BYtes共用1个Bytes
unsigned int new_Bytes1 : 1;// 占用1个新的4个Bytes
};
//12Bytes
struct S8
{
unsigned int inactive : 1;// 分配1个bit
unsigned int : 0;// 填充到下一个字边界
unsigned int new_Bytes : 1;// 占用新的4个Bytes
unsigned int : 1;// 占用1个Bit
short id; // 与new_BYtes共用1个Bytes
unsigned int new_Bytes1 : 1;// 占用1个新的4个Bytes
};
int main()
{
printf("short = %d Bytes\n", sizeof(short));
printf("unsigned int= %dBytes\n", sizeof(unsigned int));
printf("S1 = %d Bytes\n", sizeof(struct S1));
printf("S2 = %d Bytes\n", sizeof(struct S2));
printf("S3 = %d Bytes\n", sizeof(struct S3));
printf("S4 = %d Bytes\n", sizeof(struct S4));
printf("S5 = %d Bytes\n", sizeof(struct S5));
printf("S6 = %d Bytes\n", sizeof(struct S6));
printf("S7 = %d Bytes\n", sizeof(struct S7));
printf("S8 = %d Bytes\n", sizeof(struct S8));
return 0;
}
结果:
E:\Workspace\Others\C\Struct>g++ struct.c -o struct
E:\Workspace\Others\C\Struct>struct
short = 2 Bytes
unsigned int = 4 Bytes
S1 = 4 Bytes
S2 = 4 Bytes
S3 = 2 Bytes
S4 = 4 Bytes
S5 = 8 Bytes
S6 = 8 Bytes
S7 = 12 Bytes
S8 = 12 Bytes
Linux-C-struct-位段、无名字段以及填充字段
最新推荐文章于 2021-05-15 13:26:36 发布