C++ 指针帮助C++;

C++ 指针帮助C++;,c++,pointers,C++,Pointers,我很困惑。secondvalue=20如何计算?在我的评论中,我是不是遗漏了什么 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 point

我很困惑。secondvalue=20如何计算?在我的评论中,我是不是遗漏了什么

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。我哪里出错了

p1 = p2; //assign the address of secondvalue to the address of firstvalue
在这里,您将
p1
指针设置为指向
p2
所指向的对象。所以
p1
现在指向
secondvalue

不再有任何东西指向第一个值。

逐步: 您分配FV=5,SV=15,P1=FV地址,P2=SV地址

  • 将P1值(FV)设置为10。你有FV=10,SV=15
  • 将P2值设置为P1(设置SV=FV)。所以FV=10,SV=10
  • 将P1设置为P2(因此P1指向SV)
  • 将P1值设置为20(将SV设置为20)。所以FV=10,SV=20
  • 这就是结果。
    firstValue=10,secondValue=20

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

    您是否运行了代码?结果如何?您在p1=p2处的评论不正确。此语句将secondValue的加法赋值给p1,而不是firstvalue的地址