可能重复:
Returning the address of local or temporary variable内存分配:为什么这个C程序有效?
的附加功能被错误执行。它应该返回一个值而不是一个指针。 为什么打印ans和* ans_ptr时没有任何错误,并且程序甚至给出了正确的结果?我想z的变量已经超出范围,应该有分段错误。
#include <stdio.h>
int * add(int x, int y) {
int z = x + y;
int *ans_ptr = &z;
return ans_ptr;
}
int main() {
int ans = *(add(1, 2));
int *ans_ptr = add(1, 2);
printf("%d\n", *ans_ptr);
printf("%d\n", ans);
return 0;
}
阅读与1845年upvotes答案:http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed - 范围外 –