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
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.