gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:15:42 25 4
gpt4 key购买 nike

在读完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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com