题目:
找出下面code的问题,并说明原因
char* GetMemory(void)
{
char p[] = “Welcome to AMOI”;
return p;
}
void main(void)
{
char* str = NULL;
str = GetMemory();
printf(str);
}
解答1:
#include <stdio.h>
char* GetMemory(void)
{
char *p="Welcome to AMOI"; //将p定义为指针类型,只想后面的常量串,就可以正常输出了!
return p;
}
void main(void)
{
char*str=NULL;
str=GetMemory();
printf(str);
}
解答2:
char* GetMemory(void)
{
static char p[] = “Welcome to AMOI”; //static 关键字声明的变量存储在数据区,在函数返回时仍保留其内容。而局部变量在函数返回时其内存会被收回!
return p;
}
void main(void)
{
char* str = NULL;
str = GetMemory();
printf(str);
}