c++ - 为什么我的指针变量持有其他地址,但仍成功指向变量?

标签 c++ pointers

代码:

# 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 = &num;    // 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/

相关文章:

C++ 格式化日期

c++ - QTreeView 中的自定义复选框不显示

C - 将结构内部的指针重新分配给结构外部的指针

c 二叉树插入函数指针

C++ vector : push_back Objects vs push_back Pointers performance

pointers - D2 : Function Pointers won't compile

c++ - 如何使用 OpenCV trackbar 传递用户数据

c++ - openGL 3.1 是否支持实例化?

C++ 嵌套类,访问父变量

c - 指向结构中指针的指针