简体   繁体   中英

logic of pointers

I got the idea of pointers' logic generally, but there is an unclear point for me that is related to the piece of code underlain.

#include <iostream>
using namespace std;

int main ()
{
int first = 50, 
second = 150;
int * p1, * p2;

p1 = &first;         //p1 is assigned to the address of first
p2 = &second;        //p2 is assigned to the address of second
*p1 = 100;           //first's value is changed as 100 by assigning p1's value to 100
*p2 = *p1;           //now p2's value should be 100 
p1 = p2;             //I think we want to change p1's adress as p2
*p1 = 200;           //I expect that the new value of p1 should be 200

cout << first << second;

return 0;
}

Program prints first=100 and second=200, but as I commented above, I expect that p1's value is changed as 200. But It still remained as 100. What is the point of that?

You seem to be confusing a pointer value with the value a pointer points to.

*p1 = 200;           //I expect that the new value of p1 should be 200

p1 is a pointer, so its value is actually a memory location, the location of first . (something like 0xDEADBEAF). After this line:

p1 = p2;

p1 is left pointing to the memory location of second , so when doing

*p1 = 200;

its actually setting second to 200 .

指针及其值如何在代码中更改

p1 = p2 makes the p1 pointer point to the int that p2 points to. Now p1 points to second . So after that instruction, all modifications to *p1 affect the value of *p2 , so therefore also second .

You are assigning a value of 100 to the address location stored in p1, which is fine. Then you are moving this value to p2. But next you are again assigning p1 = p2,which makes the address stored in p2 to be moved to p1 which causes the trouble. Comment this line and your code will work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM