[英]Pointer incrementing in C
請考慮以下代碼:
unsigned short i;
unsigned short a;
unsigned char *pInput = (unsigned char *)&i;
pInput[0] = 0xDE;
pInput[1] = 0x01;
a = ((unsigned short)(*pInput++)) << 8 | ((unsigned short)(*pInput++));
為什么a的值是0xDEDE,而不是0xDE01?
pInput
的兩個增量之間沒有序列點 ,這會引起未定義的行為。
把它切成如下序列 :
a = ((unsigned short)(*pInput++)) << 8;
a |= ((unsigned short)(*pInput++));
a = ((unsigned short)(*pInput++)) << 8 | ((unsigned short)(*pInput++));
您正在使用后增量,在執行該行后應用++。
a將采用與執行相同的值:
a = ((unsigned short)(*pInput)) << 8 | ((unsigned short)(*pInput));
如果你想要它是0xDE01你必須這樣做:
a = ((unsigned short)(*pInput)) << 8 | ((unsigned short)(*(pInput+1)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.