请高手帮我解答下这个C语言问题

来源:百度知道 编辑:UC知道 时间:2024/05/16 08:03:23
#include<iostream.h>
char *GetMemory(void)
{
char p[]="hello world";
return p;
}
int main()
{
char *str=NULL;
str=GetMemory();
cout<<str<<endl;
return 0;
}
我运行后是乱码 能帮我解答下吗?谢谢了~~

warning C4172: returning address of local variable or temporary

#include<iostream.h>
char *GetMemory(void)
{
char p[]="hello world";
return p;
}

在这个函数中,你返回了临时变量的地址。
而临时变量的地址在函数调用完毕后就销毁了,所以str指针指向了错误的地方,输出的是内存地址随机的内容,也就是乱码。

p改成全局变量就好了。

#include<iostream.h>
char p[]="hello world";
char *GetMemory(void)
{
// char p[]="hello world";
return p;
}
int main()
{
char *str = NULL;
str=GetMemory();
cout<<str<<endl;
return 0;
}