Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What happens after we assign to a dereferenced pointer an another dereferenced pointer?

I can’t understand what happens after line *p1=10, what happens with *p2 variable, and in the end how does secondvalue variable gets 20.


#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 << '\n';
  cout << "secondvalue is " << secondvalue << '\n';
  return 0;
}

Output of command

firstvalue is 10
secondvalue is 20

I can’t understand how the secondvalue variables gets a value of 20.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If we assigned *p2=*p1 mustn’t secondvalue variable get 10?

>Solution :

p1 = p2; 

This doesn’t copy the value pointers point to, just "address" the p2 points to. Thus at this point both p1 and p2 point to the secondvalue, and changing either of them applies changes to the secondvalue

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading