簡體   English   中英

指針在C中遞增

[英]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在兩個序列點之間多次修改。 您可能得到任何預期或意外結果。 什么都不能說。

C99指出:

在前一個和下一個序列點之間,對象的存儲值最多只能通過表達式的計算修改一次 此外,只能訪問先前值以確定要存儲的值。

閱讀c-faq 3.8以獲取更詳細的說明。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM