C ++ ++ operator and pointers
I am taking my first steps in C ++ having a good background in Java. I need to remove some peculiarities of the ++ operator in C ++. Consider the following program:
#include <iostream>
using namespace std;
void __print(int x, int *px) {
cout << "(x, *px) = (" << x << ", " << *px << ")" << endl;
}
int main() {
int x = 99;
int *px = &x;
__print(x, px);
x++; __print(x, px);
x = x + 1; __print(x, px);
*px = *px + 1; __print(x, px);
*px++; __print(x, px);
return 0;
}
Surprisingly, the program prints:
(x, *px) = (99, 99) (x, *px) = (100, 100) (x, *px) = (101, 101) (x, *px) = (102, 102) (x, *px) = (102, 134514848)
It seems that * px = * px + 1 does not have the same effect on * px as it does on x. But isn't it the same? Isn't that * px == x?
source to share
The operator *
works after ++
, so it returns the wrong address value. operator precedence is important to know in C ++. take a look at this:
http://en.cppreference.com/w/cpp/language/operator_precedence
source to share
Wow, so a lot of people don't know how C ++ operators work. :)
All are right to point out that the problem is with the order of priority, exactly what the problem is, however, it seems to elude everyone.
* p ++; how a statement does exactly one thing. It increments the pointer. After evaluating and dereferencing its original value (which is ignored in this case).
int a[ 2 ] = { 10, 20 };
int* b = &a[ 0 ];
int c = *b++;
In the above example, c will be 10 and b will point to the second element (20). As the pointer b
will be evaluated before incrementing.