El3*_*1c4 0 c++ pointers pointer-address
我一般都知道了指针的逻辑,但对于我来说,有一点与下面的代码有关.
#include <iostream>
using namespace std;
int main ()
{
int first = 50,
second = 150;
int * p1, * p2;
p1 = &first; //p1 is assigned to the address of first
p2 = &second; //p2 is assigned to the address of second
*p1 = 100; //first's value is changed as 100 by assigning p1's value to 100
*p2 = *p1; //now p2's value should be 100
p1 = p2; //I think we want to change p1's adress as p2
*p1 = 200; //I expect that the new value of p1 should be 200
cout << first << second;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
程序打印首先= 100和秒= 200,但正如我在上面评论的那样,我预计p1的值会改为200.但它仍然保持为100.重点是什么?
您似乎将指针值与指针指向的值混淆.
*p1 = 200; //I expect that the new value of p1 should be 200
Run Code Online (Sandbox Code Playgroud)
p1
是一个指针,所以它的值实际上是一个内存位置,位置first
.(像0xDEADBEAF).在此之后:
p1 = p2;
Run Code Online (Sandbox Code Playgroud)
p1
是指向内存位置second
,所以在做的时候
*p1 = 200;
Run Code Online (Sandbox Code Playgroud)
它实际设置second
为200
.
归档时间: |
|
查看次数: |
1195 次 |
最近记录: |