自定义函数内部声明局部变量并返回地址,然后将另外一个变量指向返回地址,char*和char []为什么结果不同?
char* GetMemory()
{
char *p= "hello";
return p;
}
char* GetMemory()
{
char p[]= "hello";
return p;
}
上述函数通过 printf(%s\n,GetMemory());
的返回值分别为:
1、hello
2、乱码
请问这是什么原因?
另外,如果我这样写:
char *str=NULL;
str=GetMemory();
是不是错误的?(在别的地方看到的,自己不是很确定)
char* p = "hello";
其中的hello字符串是被预编译,存放与data段,是不会被销毁的;
char p[] = "hello";
本质上是
char p[6] = "hello";
这是一个局部变量,过期自动销毁了~