自定义函数内部声明局部变量并返回地址,然后将另外一个变量指向返回地址,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();
是不是错误的?(在别的地方看到的,自己不是很确定)
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
char* p = "hello";
其中的hello字符串是被预编译,存放与data段,是不会被销毁的;
char p[] = "hello";
本质上是
char p[6] = "hello";
这是一个局部变量,过期自动销毁了~
我按照你的写法,返回的都是正确的,返回hello.
代码如下:
编译环境gcc (tdm64-2) 4.8.1
include <stdio.h>
char* GetMemoryOne()
{
char *p= "hello";
return p;
}
char* GetMemoryTwo()
{
char p[]= "hello";
return p;
}
int main()
{
printf("%s\n",GetMemoryOne());
printf("%s\n",GetMemoryTwo());
}
一个是指向常量数据区,一个是动态数据区。
第二个返回的时候,函数的栈就被销毁了。