/*
* @Date: 2019-3-12
* @Author: tracycw
* @Description:
局部变量、局部指针变量的返回
为什么不能返回局部指针变量,却可以返回局部变量
函数的局部变量用作返回值时,会生成一个局部变量的拷贝用作返回值,之后局部变量会被系统回收,
函数不能返回局部变量的地址,因为如果返回局部变量的地址,系统回收后,指针指向的内容就无意义了,
但是对于静态变量也可以返回其指针。
*/
#include <iostream>
using namespace std;
char* test1(void)
{
// 栈区
char c[10] = "abcde";
return c;
}
char* test2(void)
{
// 静态存储区
static char c[10] = "abcde";
return c;
}
char* test3(void)
{
// 文字常量区
char *c = "abcde";
return c;
}
/*
c[]和str均保存在栈中;该函数返回值是保存在str指针中的c数组在栈中的存放地址,
当调用该函数时,该地址被复制到外部的指针变量中,然后,保存在栈上的c[]数组和str指针的内存空间被释放。
c[]数组的存放地址是被传送出去了的,但是,由于c[]是局部变量,在函数执行完成后,存放的内存空间就被释放,
所以,在外部通过指针访问c[]数组时,指向的内存空间无效,而且还可能出现访问非法内存的危险。
*/
char* test4(void)
{
char c[10] = "abcde";
char *str = c;
return str;
}
int* test4_max(int* a, int* b)
{
int* t;
if (*a >= *b)
{
t = a;
}
else
{
t = b;
}
return t;
}
int main()
{
cout << test1() << endl;
cout << test2() << endl;
cout << test3() << endl;
cout << test4() << endl;
int a = 3, b = 5;
cout << "max is: " << *(test4_max(&a, &b)) << endl;
system("pause");
return 0;
}
输出结果: