#include <stdio.h>
struct A
{
char t:4; // -8 ~ 7 //半个字节,但是占一个字节,还可以存半个字节
unsigned char k:4; // 0 ~ 15
unsigned char n:3; // 0 ~ 7
unsigned short i:8; // 1个字节 //如果要对其的话,对其为8
unsigned long m; // 8个字节
}; // 按最大字节对其,这个结构体为16个字节
int main(void){
printf("%d\n",sizeof(struct A));
struct A a;
a.n = 7; // 如果赋值为 8 会 有警告 warning: large integer implicitly truncated to unsigned type [-Woverflow]
printf("%d\n",a.n);
}
位域中的对齐问题
1. 用char 来定义的 变量 不会横跨在 bit[8:7] 字节,所以会对齐到 char
2. 用short 来定义的 变量 不会 横跨在 bit[16:15]字节,所以会对齐到short
3. 用int 来定义的 变量 不会 横跨在 bit[32:31]字节,所以会对齐到int