2013-07-23 84 views
1

我的CS課程正在從Java轉換到C中一小段時間。我現在正在忙於指針,我發現++運算符用於增加doens't工作時解引用。這不僅僅是一個好奇心問題。只是還沒有習慣指針概念。我只是在做一些錯誤的事情,或者與指針有關嗎?++指針上的運算符

例如:

*pointer++; Will not increment the value. 
*pointer+=1; Will increment the value. 

提前感謝!

回答

3
*pointer++; 

相當於

*(pointer++); // pointer is incremented 

,而不是

(*pointer)++; // pointee is incremented 
+0

謝謝,這樣做很有意義。 – nickcorin

2

*pointer++;幾乎等同於:

*pointer; 
pointer = pointer + 1; 

爲什麼它如此?

在表達*pointer++;++是後綴操作符,則這樣的拳頭*順從操作中執行的pointer++增量值(而不是增加值)。

*pointer += 1只是相當於:

*pointer = *pointer + 1; 

是遞增pointer指出值。

4

當你想增加值,你必須確保你使用括號。

(*pointer)++; 
2

*pointer++遞增pointer變量,而不是由值指向它。

int array[4] = {1,2,3,4}; 

int *pointer = array; 

// *pointer equals 1 

*pointer++; 

// *pointer now equals 2 
+1

這很好地解釋了這個想法,謝謝! – nickcorin

+0

接受答案,如果你喜歡它。 – Jiminion

+0

感謝您的編輯。代碼是雙倍行距? – Jiminion

2

這與運營商的優先級要做到:後遞增++比提領更高的優先級運營商*,而+=具有較低的優先級in the table of operator precedences。這就是爲什麼在第一個示例中,++應用於之後解除引用的指針,而第二個示例中+= 1應用於解除引用的結果。

+1

我注意到很晚,但你在概念上很好地解釋! ...我真的很喜歡你的答案。 –