Linux-C-struct-位段、无名字段以及填充字段

#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


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值