位域定义与结构定义相仿,其形式为:
struct 位域结构名
{
位域列表
};
其中位域列表的形式为:
类型说明符 位域名: 位域长度
但特别注意:
一个位域必须存储在同一个字节中,不能跨两个字节。如一个字节所剩空间不够存放另一位域时,应从下一单元起存放该位域。也可以有意使某位域从下一单元开始
例如:
struct size{
int a:8;
int b:2;
int c:6;
}size1;
一个简单示例:
#include <stdio.h>
typedef struct
{
unsigned char a;
unsigned int b;
unsigned char c;
}size1;
typedef struct
{
unsigned char a;
unsigned char b;
unsigned int c;
}size2;
int main(void)
{
printf("size1=%lu,size2=%lu\r\n", sizeof(size1), sizeof(size2));
return 0;
}
输出:size1=12 size2=8
解释:size1=a(1byte)+3(空闲)+b(4byte)+c(1byte)+3(空闲)=12size2=a(1byte)+b(1byte)+2(空闲)+c(4byte)=8