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?

+3


source to share


7 replies


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

+9


source


The problem is with operator priority. Try it (*px)++

;



+2


source


When you do *px++

, you are actually adding 1 to the address and then you get the value. You most likely meant (*px)++

.

0


source


* px + 1 takes the value pointed to by px and adds it by 1

* px ++ first increments the address and then takes the px value of points by

0


source


This is a priority issue:

*px = *px +1

reads like (*px) = (*px) + 1

, and since px = & x, it looks like x=x+1

.

*px++

reads like *(px++)

, so you actually move the pointer forward and get the value of what's in memory as the next position relative to x (most likely garbage).

0


source


The precedence for ++ is greater than *. Hence (px ++) is calculated. Now * (px ++) is a departure. You are not assigning or reading a value from a location. Moreover (px ++) has a location address that may not be initialized. This way you get the value of the garbage.

0


source


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.

0


source







All Articles