Help understanding this code about pointers

Hi,

I'm practicing with pointers and trying to have better understanding on how to use them
but I'm having a hard time understanding something in the following code...

1
2
3
4
5
6
7
8
9
10
11
12
1. int a = 5, b = 10;
2. int *p1, *p2;
    
2. p1 = &a; // p1 now points to a  
4. p2 = &b; // p2 now points to b
    
5. *p1 = 10; // p1 new value is 10   
6. p1 = p2;  // assign address from p2 to p1   
7. *p1 = 20; // confusion here, I was expecting to get 20 for "a" since we are assigning a new value
    
8. cout <<"A value: " << a << endl;    
9. cout <<"B value: " << b << endl;


why when compile the result is a = 10 and b = 20?

Where did "b" became 20?

Shouldn't "a" be 20 since the last assignment was done to p1 in line 7?

Can someone be so kind and go through each line and explain what’s happening throughout the program?

Thanks a lot!
Last edited on
Look the statements.

p2 = &b; // p2 now points to b
p1 = p2; // assign address from p2 to p1
*p1 = 20; // confusion here, I was expecting to get 20 for "a" since we are assigning a new value
 
6. p1 = p2;  // assign address from p2 to p1    


This is your culprit. The assignment circumvents a and now points to b so the assignment to the value of 20 effects b not a.
It will be interesting to you to consider the following code

1
2
3
4
5
6
7
8
9
10
11
int a = 5;
int b = 10;
int &ra = a;
int &rb = b;
    
ra = 10;
ra = rb;
ra = 20;
    
cout <<"A value: " << a << endl;    
cout <<"B value: " << b << endl; 


Compare it with your original code.:)
I think I got it, since we assigned the address from p2 to p1 now both are pointing to the same address.

1
2
3
p2 = &b; // p2 now points to b
p1 = p2; // assign address from p2 to p1 
*p1 = 20; //here p1 is assigning 20 to p2 since p1 is also referencing p2's address so, any change made to p1 will be done to p2 


Thanks a lot for clarifying this.
Last edited on
*p1 = 20; //here p1 is assigning 20 to p2 since p1 is also referencing p2's address so, any change made to p1 will be done to p2

That description is confusing.
p1 and p2 simply both contain the address of variable b.
They're still independent between themselves.
You can think that pointers are simply variables which contain a number, representing a memory address.
The way I understand it is that they will be basically pointing to the same location in memory until p1 is reassigned to the location for "a" that's what I meant with...

*p1 = 20; //here p1 is assigning 20 to p2 since p1 is also referencing p2's address so, any change made to p1 will be done to p2

I think I now have a better understanding. Sorry if my comments dont make too much sense.

Thank you all very much for your help
Topic archived. No new replies allowed.