在读完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 ?因为它们共享相同的内存地址。据我所知,一个内存地址不能有 2 个不同的值。
我的推理如下:
*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
任何帮助将不胜感激。提前致谢。
最佳答案
代码:
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
关于C++:误解内存地址和指针的复制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58792661/