开发者

Adding to the location of a pointer in C++

开发者 https://www.devze.com 2023-02-21 20:16 出处:网络
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?

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

精彩评论

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

关注公众号