I have question on 'Declaring pointers'

Write your question here.

Hi I am Joon who is studying C++ with this website.

I have question about one of part. At the part 'Declaring pointers' the example

// more pointers
#include <iostream>
using namespace std;

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

p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed to by p1 = 10
*p2 = *p1; // value pointed to by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1=20; // value pointed by p1 = 20

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
}


I don't really understand why with all '*p1=20' the firstvalue has to be 10 not 20. When it comes to secondvalue, it makes sense since *p2=*p1.

could you explain why is it like that?

I really aprreciate on this website to lecture me informative C++.
Thank you.

welcome to the website.

Please use code tags for all of your code - http://www.cplusplus.com/articles/jEywvCM9/

Read below :)

Last edited on
If you're wondering why firstvalue stayed at the value of 10, it's because the pointer p1 was changed to point to the address of secondvalue. Then when you did *p1 = 20, it actually set the secondvalue to 20, but not firstvalue since p1 was no longer pointing toward it.

Edit:

p1 = p2; // p1 = p2 (value of pointer is copied)

The code above is where the p1 was changed to point toward the secondvalue instead of firstvalue
Last edited on
I think the output is that both are 20, right?

But what do you want to know?
Gamer2015 wrote:
I think the output is that both are 20, right?

But what do you want to know?


Actually, firstvalue would output 10, since the value of firstvalue was only changed once.
└ TarikNeaj Thank you for reply. I haven' read codes tags yet but next time I will follow that steps

└ germanchocolate Thank you very much now I get the concept more clearly. really appreciate it :)
Topic archived. No new replies allowed.