Pointers

I'm following the tutorials on the site and I got to pointers.

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 by p1 = 10
  *p2 = *p1;         // value pointed by p2 = value pointed by p1
  p1 = p2;           // p1 = p2 (value of pointer is copied)
  *p1 = 20;          // value pointed by p1 = 20
  
  cout << "firstvalue is " << firstvalue << endl;
  cout << "secondvalue is " << secondvalue << endl;
  return 0;
}


It's the example in the tutorial and it works, but I don't understand why firstvalue ends as 10 and secondvalue as 20. Shouldn't it be the opposite?
Last edited on
Look through the lines of the code, analyze the comments and see how the pointers are being using. Note that line 12 is the only one that modifies firstvalue, while line 13 and line 15 are modifying secondvalue.
Oh, I got it. Since p2 was copied to p1, any change to *p1 is no longer a change to firstvalue, but to secondvalue. Apparently, I had forgotten that the assignment operation worked from right to left. Thank you.
Exactly. You seem to understand it.
doh, even though this is already resolved, I made a diagram to show it.

I'll post it anyway. Pointers are much easier to understand visually, IMO:

http://i47.tinypic.com/25zm6wp.png
Topic archived. No new replies allowed.