Pointers

Hi, I am going through the tutorials on here for some revision, and I am struggling to understand some code relating to pointers. This is the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  // more pointers
#include <iostream>
using namespace 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.
Hi,

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.
Is that right?


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.

https://en.cppreference.com/w/cpp/language/value_category

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



I understand now, (Not sure if I just mistyped earlier, or if I did in fact misunderstand, its way past my bed time :D )

Thank you for your help, greatly appreciated
Topic archived. No new replies allowed.