c++pointerspointer-address

logic of pointers


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?


Solution

  • 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.