pointer

why firstvalue = 10 and second = 20 ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 please help me with this code 

// 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 by p1 = 10
*p2 = *p1; // value pointed 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 << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}

i can not understand why firstvalue = 10 not 20 ???
Begins as 5:
int firstvalue = 5;

Changed to 10:
*p1 = 10

That's it.

When do you think firstValue becomes 20? The comments explain exactly what's happening.
Last edited on
*p1 (and similar syntax, p1[0]) IS firstvalue. If you change firstvalue, you changed *p1, and if you change *p1, you change firstvalue. The pointer (p1) is using the exact same memory location because you told it to (p1 = &firstvalue). so if you modify that memory location, you change the value, no matter how you get that value back out (by its firstvalue name or by going to the memory location directly via a pointer, its still the same data).

changing p1 itself is NOT the same thing:
*p1 = 3; //firstvalue is changed.
p1 = 0; //firstvalue did NOT change. This is the pointer. it NO LONGER points to first value if you do this (and will crash, actually, due to trying to access memory that you should not).

does that make sense at all?

thanks to explain but i want to understand what this two line means ?

p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20
p1 = p2;
The thing that p2 is pointing at - now p1 points at the same thing.

*p1 = 20; // value pointed by p1 = 20
The thing p1 is pointing at - set its value to 20.
Topic archived. No new replies allowed.