2011-04-04 70 views
0

我有int foo,它的地址是一個整數。 如何添加到foo指向一行的整數?添加到C++中的指針位置

解決方案:

(*(int *)foo)+=1 

這是我如何處理它。

+2

你的意思foo是一個int指針?即。 'int * foo' – GWW 2011-04-04 21:09:40

+2

請用一個例子來說明你的問題。 – jonsca 2011-04-04 21:10:42

+0

你的意思是你有一個存儲在「int」中的指針值? – 2011-04-04 21:12:35

回答

6

要添加到指針指向的值:

int * pointer; 
int value; 
(*pointer) += value; // parans for clarity, not necessarily needed 
+0

不,這會覆蓋舊值。 – delnan 2011-04-04 21:10:59

+0

你的意思是'+ ='? – 2011-04-04 21:11:52

+0

是的,修好了。 :) – ssube 2011-04-04 21:12:06

0
int a = 4; 
int* foo = &a; 
// and now the one line you asked 
*foo = *foo + 2; // a = 6 
0

如果你是一個遞增和感覺寫它的最短路徑(++ *指針)。例如:

int i = 0; 
int* ip = &i; 

cout << i << endl; 
++*ip; 
cout << i << endl; 

輸出:

0 
1