(23条消息) C++ 函数返回局部变量地址和引用_最后冰吻free的博客-CSDN博客_c++函数返回地址

PHOTO EMBED

Thu Nov 24 2022 06:10:39 GMT+0000 (Coordinated Universal Time)

Saved by @leawoliu

#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
content_copyCOPY

https://blog.csdn.net/CodeHouse/article/details/107239188