请指出该程序的错误。
#include <iostream.h>int *p;void Function()
{
int n;
n = 25;
p = &n;
}void main()
{
Function();
cout<<"value of *p: "<<*p<<endl;
}
#include <iostream.h>int *p;void Function()
{
int n;
n = 25;
p = &n;
}void main()
{
Function();
cout<<"value of *p: "<<*p<<endl;
}
应该改成
#include <iostream.h>int *p;void Function()
{
int n;
n = 25;
p = new int;
*p = n}void main()
{
Function();
cout<<"value of *p: "<<*p<<endl;
}
int n;
虽然是个局部变量,他在退出Function函数后会被释放,但被释放的这2byte在cout语句执行前被分配掉的可能性比较小。这里面的值将保持不变。
不过一旦这2byte被分配掉了,里面是什么值都有可能。
value of *p 25