可能重复:
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输出随机数?
您正在创建一个指向堆栈变量的指针,该堆栈变量被销毁,然后取消引用指针,产生未定义的行为 – 2012-01-03 15:52:51
未定义的行为,这意味着您可以获得预期的输出(http://ideone.com/VMYzG)或某些其他结果(http://codepad.org/OiN8n1L0) – UncleBens 2012-01-03 16:20:27