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

时间:2020-10-03 18:54:29

标签: 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”。 为什么?

1 个答案:

答案 0 :(得分:3)

您的代码是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;
}