Why don't "a" and "b" have equal values of 20?

Why don't "a" and "b" have equal values of 20?

Since "p1 = p2," and " *p1 = 20 " essentially means " a = 20, " I assumed a = 20 and b = 20, but the actual result is a = 10 and b = 20.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using namespace std;

int main( )
{
   int a = 5, b = 8;
   int *p1, *p2;
   p1 = &a;
   p2 = &b;
  *p1 = 10;
   p1 = p2;
  *p1 = 20;
   cout << a << endl;
   cout << b << endl;
}
You're assigning p1 the address of p2, thus when changing the contents of p1 to 20, you're actually changing the value of b.
Illustrating Bogeyman answer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int a = 5, b = 8; // p1    a = 5  
int *p1, *p2;     // p2    b = 8
   
 p1 = &a;   // p1 --> a = 5 
 p2 = &b;   // p2 --> b = 8
   
*p1 = 10;   // p1 --> a = 10 
            // p2 --> b = 8
  
 p1 = p2;   // p1 -_   a = 10
            // p2 ---> b = 8
   
*p1 = 20;   // p1 -_   a = 10
            // p2 ---> b = 20 
Because if you go step by step through your code there is no reason for it to equal 20.
1
2
3
4
5
6
7
8
9
10
//                        a   b   p1  p2
int a = 5, b = 8;  //     5   8   -     -
   int *p1, *p2;   //     5   8   -     -
   p1 = &a;        //     5   8   a     -
   p2 = &b;        //     5   8   a     b
  *p1 = 10;        //     10  8   a     b
   p1 = p2;        //     10  8   b     b
  *p1 = 20;        //     10  20  b     b
   cout << a << endl;
   cout << b << endl;
Topic archived. No new replies allowed.