int a = 5, b = 10; //A = 5, B = 10
int *p1, *p2; //Create pointers that can hold addresses
p1 = &a; //the p1 ptr will now hold the address of a so *p1 = 5;
p2 = &b; //the p2 ptr will now hold the address of a so *p2 = 10;
*p1 = 10; //the value of *p1 now equals 10, so a = 10
p1 = p2; //the address of p1 is now equal to p2 so a and b = 1
*p1 = 20; //the value of p1 is now 20 so a = 20 <--Doesnt this tell a it ='s 20?
//results are a = 10 and b = 20;
//I said a = 20 and b = 20
Line 7 is where you go wrong. The value of p1 became the value of p2, which is the address of b. You didn't change anything about the values of a or b.
A pointer is like any other variable type, the trick is that its value is a memory address.
#include <iostream>
int main()
{
int a = 5, b = 10; //A = 5, B = 10
int *p1, *p2; //Create pointers that can hold addresses
p1 = &a; //the p1 ptr will now hold the address of a so *p1 = 5;
std::cout << "1. " << *p1 << std::endl;
p2 = &b; //the p2 ptr will now hold the address of a so *p2 = 10;
std::cout << "2. " << *p2 << std::endl;
*p1 = 10; //the value of *p1 now equals 10, so a = 10
std::cout << "3. " << *p1 << " " << a << std::endl;
p1 = p2; //the address of p1 is now equal to p2 so a and b = 10
std::cout << "4. " << a << " " << b << std::endl;
*p1 = 20; //the value of p1 is now 20 so a = 20 <--Doesnt this tell a it ='s 20?
std::cout << "5. " << *p1 << " " << a << std::endl; // *p1 is dereferenced p1 which is "*&a" which is a
//results are a = 10 and b = 20;
std::cout << "6. " << a << " " << b << std::endl;
//I said a = 20 and b = 20
}
Yes thats the best way, but he has to understand that p1 does not contain the address of "a" anymore but rather the address "b". because of the line p1 = p2;
That's quite right. Both pointers point to the same address which happens to be the location of a. Also dereferecing the pointers doesn't change the value of the varaiable being pointed to which is what the printout shows. He should printout *p1 andf *p2 along with p1 and p2 and &a and &b to demonstrate the points you quite rightly raise.