struct People
{
int id;
int age;
};
struct People_bit
{
int id : 4;
int age : 4;
};
int main()
{
struct People p;
struct People_bit p_bit;
printf("struct People : %d Byte\n", sizeof(People)); // output: 8
printf("struct People_bit : %d Byte\n", sizeof(p_bit)); // output: 4
return 0;
}
============================================================================
位域(bit-field)
常用于状态量,即1位代表2个状态,2位代表四个状态,等等。
注意事项:
1. 类型只能是:int,unsigned int,signed int。
2. 以上三种类型在我编译器下都是4Byte(32bit)。
3. 位域分配的机制就是一次申请4个Byte(32位)的内存空间,然后用于分配,当32位被用完,再申请32位。
如上例,People_bit结构体申请了一次4Byte内存,我们定义了两个长度为4位的变量,那么没有占满32位。因此结构体长度位4Byte。