// more pointers
#include <iostream>
usingnamespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed to by p1 = 10
*p2 = *p1; // value pointed to by p2 = value pointed to by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed to by p1 = 20
cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
}
I understand it mostly, but I dont understand how secondvalue prints to console as 20, and firstvalue as 10. I thought it would be the opposite, but I am obviously misunderstanding something here. If anyone could help explain this, it would be appreciate.
You can add more cout statements to see what happens at each stage, or use a debugger to see what is happening.
line 12 sets firstvalue to 10.
line 14 means that p1 is really p2 (the address of p2 is assigned to p1), so line 15 sets secondvalue to 20. So that demonstrates how confusing pointers can be, therefore how careful one has to be when using pointers.
OK I think I am following that. So say &firstValue is 1, and &secondValue is 2. P1 stores 1 initially, and p2 stores 2 initially. Then p1 = p2 sets p1 and p2 both to store address 1, and now neither pointer is storing the address of the secondValue. Is that right?
The p1= p2 is really confusing to me, the way I read that, I assumed it was p1 is p2, so set both to store the seondvalue, but I guess I have that backwards.
Unfortunately no. Assignment is a right to left operation. The expression on the right is evaluated, then it's value is assigned to the variable on the left. It's easy to see why that is if you think about what the expression on the rhs could be in a general sense: a mathematical expression like 2 + 3 ; a literal value like 'a' or 5 say. There is a whole lot of material about that, if you are interested. Basically the expression on the rhs is an rvlaue, on the left is an lvalue, and there various value categories , an expression like 2 + 3 is a prvlaue (pure rvalue) expression.
The p1= p2 is really confusing to me, the way I read that, I assumed it was p1 is p2, so set both to store the seondvalue, but I guess I have that backwards.
You are correct: p2 is assigned to p1 so both address are equal to p2; both p1 and p2 refer to secondvalue