开发者

Adding to the location of a pointer in C++

I have int foo which has the address of an integer in it. How do I add to the integer tha开发者_如何学运维t foo is pointing to in one line?

Solution:

(*(int *)foo)+=1

This is how I handled it.


To add to the value the pointer is pointing to:

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


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


If you are incrementing by one and feel like writing it the shortest way (++*pointer). Example:

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

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

Output:

0
1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜