Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

c++ pointer problem 2 #include <iostream> using namespace std; int main () { int

ID: 3559488 • Letter: C

Question

c++ pointer problem 2

#include <iostream>

using namespace std;

int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;
*p2 = *p1;
p1 = p2;
*p1 = 20;

cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0; }

Output:

firstvalue is 10
secondvalue is 20

I am confusion, i see this p1=p2 not firstvalue = 20 and secondvalue also 20?
Please explain this problem?

Explanation / Answer

#include <iostream>

using namespace std;

int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue; // p1 holds address of firstvalue so *p1 = 5;
p2 = &secondvalue; // p2 holds address of secondvalue so *p2 = 15;
*p1 = 10; // *p1 = 10; now fisrt value holds value 10;
*p2 = *p1; // *p2 = *p1; since *p1 = 10 so *p2 = 10 secondvalue holds value 10;
p1 = p2; // p1 = p2; now p1 holds same address as p2 so *p1 holds 10 so fisrtvalue holds 10
*p1 = 20; // *p1 = 20 so since p1 holds address of secondvalue. secondvalue holds value 20.
// now firstvalue is 10
// secondvalue is 20

cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0; }

Output:

firstvalue is 10
secondvalue is 20

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote