#include <iostream>char*GetMemory(){char p[]="Hello!\n";return p;}void main(void){char *str =NULL;str=GetMemory();printf(str);} 哪里有错啊?
3 回答

Helenr
TA贡献1780条经验 获得超4个赞
你的P是个数组,然后是局部变量,在GetMemory函数中有效。
函数结束以后,数组内存会被系统回收。你虽然返回了P,但是返回的p实际上是个指针。指向已经被回收的内存Hello!\n。所以不会打印出什么东西的。
你要打印出东西就必须在主函数就把str的内存分配好,并且用传址的形式传入GetMemory

繁花如伊
TA贡献2012条经验 获得超12个赞
#include <iostream.h>
#define NULL 0
char *GetMemory(){
char p[]="Hello!\n";
return p;
}
void main(){
char *str =NULL;
str=GetMemory();
printf("%s",str);
}
- 3 回答
- 0 关注
- 275 浏览
添加回答
举报
0/150
提交
取消