2016-05-03 93 views
-2

我很困惑。 secondvalue如何= 20?在评论中是我认为正在发生的事情,我在某处丢失了什么?指针帮助C++

int firstvalue = 5, secondvalue = 15; 
int *p1, *p2; 

p1 = &firstvalue; //assign the address of firstvalue to p1 
p2 = &secondvalue; //assign... secondvalue to p2 
*p1 = 10; //assign 10 to the value pointed by p1 (firstvalue now = 10) 
*p2 = *p1; //assign the value pointed by p1 to the value pointed by p2 
      //secondvalue = 10, firstvalue = 10 
p1 = p2; //assign the address of secondvalue to the address of firstvalue 
     //address of firstvalue = address of secondvalue 
*p1 = 20; //assign 20 to the value pointed by p1 (firstvalue = 20) 

输出应该 firstvalue = 10和secondvalue = 20,但是从我的理解firstvalue = 20,secondvalue = 10.在哪里我会错呢?

+0

你是否运行过代码?结果是什么? – Igor

+0

您在p1 = p2的意见不正确。此声明将secondValue的地址分配给p1,而不是第一个值的地址 –

回答

4
p1 = p2; //assign the address of secondvalue to the address of firstvalue 

在这里你设置p1指针在什么p2点到另一个点。所以p1现在指向secondvalue

没有什么东西指向firstvalue了。

+0

有意义 - 感谢您清理它 –

0

Step by step: 您指定FV = 5,SV = 15,P1 = FV的地址,P2 = SV的地址。

  1. 您P1值(FV)设置为10。您有FV = 10,SV = 15
  2. 您组P2的值P1(设置SV = FV)。因此FV = 10,SV = 10。
  3. 您将P1设置为P2(因此P1指向SV)。
  4. 您将P1值设置为20(您设置SV = 20)。因此FV = 10,SV = 20。

这就是结果。 firstValue = 10,secondValue = 20

0

firstValue = 10和secondValue = 20的值是真, 在代码的第7行(即,P1 = P2)的指针P1现在指向P2的地址(这实际上是第二个值的地址)。现在,将* p1的值更改为20时,它将更改secendValue的值。