0

I got the idea of pointers' logic generally, but there is an unclear point for me that is related to the piece of code underlain.

#include <iostream>
using namespace std;

int main ()
{
int first = 50, 
second = 150;
int * p1, * p2;

p1 = &first;         //p1 is assigned to the address of first
p2 = &second;        //p2 is assigned to the address of second
*p1 = 100;           //first's value is changed as 100 by assigning p1's value to 100
*p2 = *p1;           //now p2's value should be 100 
p1 = p2;             //I think we want to change p1's adress as p2
*p1 = 200;           //I expect that the new value of p1 should be 200

cout << first << second;

return 0;
}

Program prints first=100 and second=200, but as I commented above, I expect that p1's value is changed as 200. But It still remained as 100. What is the point of that?

Matt
  • 22,721
  • 17
  • 71
  • 112
El3ctr0n1c4
  • 400
  • 2
  • 7
  • 18
  • `p1 = p2` your assignment changed the value of pointer, after that `p1` points to the same value as `p2`, i.e. `&second` – Gene Bushuyev Nov 07 '11 at 22:42
  • I didn't understand what you want with `p1 = p2;`. That will make `p1` to point to the same place as `p2`, so now both `p1` and `p2` will point to the same variable `second`. – lvella Nov 07 '11 at 22:44

4 Answers4

7

You seem to be confusing a pointer value with the value a pointer points to.

*p1 = 200;           //I expect that the new value of p1 should be 200

p1 is a pointer, so its value is actually a memory location, the location of first. (something like 0xDEADBEAF). After this line:

p1 = p2;

p1 is left pointing to the memory location of second, so when doing

*p1 = 200;

its actually setting second to 200.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
3

How the pointers and their values change in the code

ahj
  • 745
  • 1
  • 6
  • 13
  • 1
    This is a nice graphical way of representing what's going on, but it is hard to read. Consider breaking the picture into 4, one for each stage, and enlarging them, the font size in particular. – rcollyer Nov 08 '11 at 18:16
1

p1 = p2 makes the p1 pointer point to the int that p2 points to. Now p1 points to second. So after that instruction, all modifications to *p1 affect the value of *p2, so therefore also second.

Jesse Emond
  • 7,180
  • 7
  • 32
  • 37
0

You are assigning a value of 100 to the address location stored in p1, which is fine. Then you are moving this value to p2. But next you are again assigning p1 = p2,which makes the address stored in p2 to be moved to p1 which causes the trouble. Comment this line and your code will work as expected.

Tej
  • 11
  • 3