函数内部变量(字符类型变量等)输出出现乱码

#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

https://bbs.csdn.net/topics/390557647

https://baike.baidu.com/item/memset/4747579?fr=aladdin

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值