C ++:误解了内存地址和指针的复制值

问题描述 投票:0回答:1

[我以为我在通过this example之前就了解了指针的概念(请参阅“声明指针”),第二个示例,其中指出以下内容:

#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 to by p1
  p1 = p2;           // p1 = p2 (value of pointer is copied)
  *p1 = 20;          // value pointed to by p1 = 20

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

具有结果:

firstvalue is 10
secondvalue is 20

我的问题是:为什么*p1=firstvalue不是20?因为它们共享相同的内存地址。据我所知,一个内存地址不能有两个不同的值。我的理由如下:

*p1 = 10 //firstvalue=10, *p2=secondvalue=15
*p2 = *p1 //*p1=firstvalue=secondvalue=*p2=10
p1 = p2 //*p1=*p2, now firstvalue and secondvalue share the same memory adress 
*p1 = 20 //*p2=*p1 (because they have the same memory adress) so firstvalue=secondvalue=20

任何帮助将不胜感激。提前致谢。

c++ pointers copy memory-address
1个回答
0
投票
代码:

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 to by p1 p1 = p2; // p1 = p2 (value of pointer is copied) *p1 = 20; // value pointed to by p1 = 20

可以改写为

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

© www.soinside.com 2019 - 2024. All rights reserved.