一、题目
下面代码的运行结果为?
int main()
{unsigned char puc[4];struct tagPIM{unsigned char ucPim1;unsigned char ucData0 : 1;unsigned char ucData1 : 2;unsigned char ucData2 : 3;}*pstPimData;pstPimData = (struct tagPIM*)puc;memset(puc,0,4);pstPimData->ucPim1 = 2; pstPimData->ucData0 = 3;pstPimData->ucData1 = 4;pstPimData->ucData2 = 5;printf("%02x %02x %02x %02x\n",puc[0], puc[1], puc[2], puc[3]);return 0;
}
二、解析
我们先看结构体:
struct tagPIM{unsigned char ucPim1;unsigned char ucData0 : 1;unsigned char ucData1 : 2;unsigned char ucData2 : 3;}*pstPimData;
ucPim1占用一个字节,剩余unData占用1个字节,共占用两个字节。
unsigned char puc[4];给了我们4个字节pstPimData = (struct tagPIM*)puc;结构体只占用2个字节
我们再看赋值
pstPimData->ucPim1 = 2; pstPimData->ucData0 = 3;pstPimData->ucData1 = 4;pstPimData->ucData2 = 5;
最后用16进制打印出 puc 的每个元素,4位二进制码为1组,答案是
02 29 00 00