为什么 printf 打印 7,尽管变量 a 是函数 fun() 的局部变量,并且一旦控件从函数 fun() 返回后不应再存在。
这是C代码
#include<stdio.h>
main()
{
int *fun();
int *c=fun();
printf("%d",*c);
getch();
}
int *fun()
{
int a=7;
return(&a);
}
输出:7
最佳答案
这是因为即使变量不再存在,它所在的内存位置还没有被其他东西使用。因此,指针仍指向内存位置,其中位包含值为 7 的 int
。
但这绝对是未定义的行为。您不应该依赖它。
关于c - 对输出感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11151875/