代码:
# include <iostream>
using namespace std;
int main(){
int num = 10, *p;
*p = num;
cout<<" &num = "<<&num<<" p = "<<p<<endl<<" *p = "<<*p<<endl;
return 0;
}
输出:&num = 0x7ffeef0908c8 p = 0x7ffeef0908e0
*p = 10
理论上,“p”的内容等于“num”的地址。但这不是在这里发生。但是,它仍然成功指向“num”。
为什么?
最佳答案
您的代码是UB。看起来好像它可以正常工作,但是很可能损坏或崩溃系统,或者可能发生其他任何事情(通常很糟糕)。
int num = 10, *p; // this leaves p unitialized; you don't know to what it points
*p = num; // OUCH! This is UB because you dereference an unitialized pointer
这是一个可行的替代方案:#include <iostream>
using namespace std;
int main(){
int num = 10, *p;
p = # // make the pointer point to to num using the address
cout<<"&num = "<<&num<<" num = "<<num<<" p = "<<p<<" *p = "<<*p<<endl;
*p = 77; // change the value pointed to
cout<<"&num = "<<&num<<" num = "<<num<<" p = "<<p<<" *p = "<<*p<<endl;
return 0;
}
关于c++ - 为什么我的指针变量持有其他地址,但仍成功指向变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64187874/