0

I have this code in c++.

#include<iostream>
using namespace std;

int main()
{
  int z;
  int v1,v2;
  int *p1,*p2;

  p1 = &v1;
  p2= &v2;

  *p1 = 15; // value pointed by p1 is 10
  *p2 = *p1; // value pointed ny p2 is the value pointed by p1 which at the moment is 10.
  p1 =p2; //p1 is assigned the value of p2 which is 10
   *p1 = 20; // the value pointed by p1 is 20;

   cout<<"v1:"<<v1<<endl;
   cout<<"v2:"<<v2<<endl;

   cin>>z;
}

Here the output is v1:15, v2:20. I am little confused here, p1 points to address of v1,the latest value pointed by p1 is 20 not 15, so how come the output shows v1:15

With the output i assume that the value assigned immediately to the pointer after the pointer is pointing to the address of a variable counts rather than the latest value.Is that correct?

1
  • 1
    The value of p2 is &v2, not 10. Pointers hold addresses. Commented Aug 25, 2014 at 3:59

1 Answer 1

4

You are reassigning p1 to point to the same location as p2, which happens to point to v2. This means that when you are setting the value pointed to by p1 to 20, you are writing to v2 and not to v1.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.