//int main() //{ //unsigned char puc[4]; //struct tagPIM //{//开辟四个内存 // unsigned char UcPim1;//开辟一个字节,全部被自己占用 // unsigned char UcData0:1;//只能开辟一个字节,char型,自己占用2Bit // unsigned char UcData1:2;//char型,自己占用2Bit // unsigned char UcData2:3;//剩下的4bit都给它 // //}*pstPimData;//指针pstPimData指向结构体tagPIM // //pstPimData = (struct tagPIM*)puc;//位段存储 //memset(puc, 0, 4);//将内存全部清空为00000000 00000000 00000000 00000000 //pstPimData->UcPim1 = 2;//开辟一个字节,2的二进制00000010,全放,但是用完整个位段 //pstPimData->UcData0 = 3;//3的二进制00000011,只能占用1个bit,为1 //pstPimData->UcData1 = 4;//4的二进制00000100,只能占用2个bit,为00 //pstPimData->UcData2 = 5;//5的二进制00000101,能占用剩下的3个bit,为101 合并UcData0->2并补0,变为00101001,%02x为十六进制为29 //printf("%02x %02x %02x %02x\n", puc[0], puc[1], puc[2], puc[3]);//02 29 00 00 //return 0; //} //联合体存在对齐---共用空间 union Un { short s[7];//2(最大对齐数short为7)*7(个数)=14 int n//最大对齐数4 //4和2的最大对齐数是4,所有14应浪费到16(4的倍数),所有16 }; int main() { printf("%d\n", sizeof(union Un));//16 }