#include <iostream>
using namespace std;
int A(){
int a = 10;
return a;
}
//warning C4172:returning address of local variable or temporary: a
int* A1(){
int a = 20;
return &a;
}
//warning C4172:returning address of local variable or temporary: a
int& A2(){
int a = 30;
return a;
}
//warning C4172:returning address of local variable or temporary: buf
char* Buf(){
// 字符串是栈中,函数执行结束就被销毁,指针就成为野指针,所以就乱码;同样解释上面(可以将其拷贝到一个已经分配好空间的全局变量中)
char buf[] = "111";
return buf;
}
char* TempBuf()
{
char* buf = new char[4];
buf[0] = 'T';
buf[1] = 'm';
buf[2] = 'p';
//buf[3] = '\0';//这句不加就乱码,因为不加则会存在垃圾数据,需要作清空操作
return buf;
}
char* BufPro(){
// 整个程序结束后,buf才释放,所以没乱码,关于静态变量参考“参考”
static char buf[] = "222";
return buf;
}
int main()
{
int a = 0;
a = A();
cout << "a:" << a << endl;
int* b = A1();
cout << "*b:" << *b << endl;//可能乱码
int& c = A2();
cout << "c:" << c << endl;//可能乱码
char* d= Buf();
cout << "*d:" << d << endl;//我输出的时候乱码了
char* f = TempBuf();
cout << "*f:" << f << endl;//我输出的时候乱码了,加'\0'则OK
char* e = BufPro();
cout << "*e:" << e << endl;
cin.get();
//getchar();
//system("pause");
return 0;
}
解决:char* buf()中变量除了加static还有什么其他方式防止乱码,修改代码
参考:
https://www.cnblogs.com/wangj08/p/3472486.html