刚才在看 C++ Primer 发现在函数那一章讲函数返回值时, 对于返回值能否是引用或指针的问题进行了解答. 但是描述的不是很具体, 在翻阅了一些博客后在此做个简单的笔记
#include <cstdio> using namespace std; int *back() { int x = 1; int *p = &x; return p; } int *BACK() { int x = 2; int *p = &x; return p; } int main(void) { int *p = back(); printf("%d\n", *p); // 输出1 int *q = BACK(); printf("%d\n", *p); // 输出2 return 0; }
#include <cstdio> #include <cstdlib> using namespace std; int *back() { static int x = 1; int *p = &x; return p; } int *BACK() { int x = 2; int *p = &x; return p; } int *heap() { int *p = (int *)malloc(sizeof(int)); return p; } int *HEAP() { int *p = (int *)malloc(sizeof(int)); return p; } int main(void) { int *p = back(); printf("%d\n", *p); //输出 1 int *q = BACK(); printf("%d\n", *p); //输出依然是 1 p = heap(); printf("%p\n", p); //输出00000000001c13f0 q = HEAP(); printf("%p\n", p); //输出依然是00000000001c13f0 return 0; }