Preview:
#include <iostream>

using namespace std;

//局部变量存放在栈区,不要在函数中返回局部变量的地址,函数退出后,局部变量的内存被系统自动释放
int* print()
{
	int a = 10;
	
	return &a;	
}

int main()
{
		int *p = print();
		cout<<*p<<endl;//第一次打印正确的值,是因为编译器做了一次保留;
		cout<<*p<<endl;//第二次这个数据就不会保留了;
	
		return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter