c++ - 怎么了?悬挂指针?

标签 c++

<分区>

Possible Duplicate:
Returning the address of local or temporary variable
Can a local variable's memory be accessed outside its scope?

#include<iostream>
using namespace std;

int *p = NULL;

void 
fun(void){
    int i = 10;
    p = &i;
}

int 
main(void){
    fun();
    cout<<*p<<endl; //#1
    cout<<*p<<endl; //#2
    return 0;
}

我认为#1 和#2 会输出相同的结果,但为什么#1 输出 10 而#2 输出一个随机数呢?

最佳答案

这只是未定义的行为。在该变量超出范围后,您正在使用指向局部变量的指针。任何事情都可能发生。

关于c++ - 怎么了?悬挂指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8714822/

相关文章:

java - 试图将一堆 C++ 代码转换为 Java - if 语句

c++ - 视觉C++ : buggy towupper

c++ - Qt 元对象系统 : emit signal using a string with its name

c++ - 继承抽象迭代器接口(interface)

c++ - 编译 C++ : undefined reference

c++ - gcc 4.8.1 是否支持 C++11 垃圾回收?

c++ - 将多个实现提取到静态库中

c++ - 我怎么知道临时对象何时被创建和销毁?

c++ - 安装 Open GRM thrax 时出错

c++ - C++ 运行时如何确定抛出异常的类型?