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
精彩评论