+ 1

Pointer Reference to changing values?

Today through trial and error and playing with pointers, that if you have a pointer to a variable whose value is getting changed the memory address moves? The line I tested with is int userCounter = 0; int *pUserCounter = &userCounter; *pUserCounter++; Upon cout I noticed that the initial value is zero, yes great. But then the next value was a different memory address and then the next was 0 again. I know realized that having a pointer to an object does not give it the full effect to edit the object? I know the difference between pass by reference and pass by value and how to make a reference, which is using the & operator as well. But why did that particular output happen? I thought I was changing the value at that memory address so why did it display a different address?

6th Dec 2018, 2:41 PM
Aqua Crow
Aqua Crow - avatar
2 Respuestas
+ 4
It's a operator precedence issue, see https://en.cppreference.com/w/cpp/language/operator_precedence As you see the postfix operator has a higher precedence and is evaluated before the dereference operator. So it increments the pointer instead of the value pointed to by the pointer. If you want to increment the value pointed to by the pointer then you should use brackets, (*p)++;
6th Dec 2018, 2:52 PM
Dennis
Dennis - avatar
+ 1
Oh damn. You are the best. I did not think it would be that simple. I over thought the process. Hahaha Thanks Dennis.
6th Dec 2018, 2:57 PM
Aqua Crow
Aqua Crow - avatar