char *fun()
{
static char str[] = "hello world";
return str;
}
int main()
{
char *p = fun();
puts(p);
return 0;
}
插入代码片
答案:随机值
出现问题的原因:str是局部的,fun函数结束,str生命周期就结束了
解决办法:延长生命周期
1、static
2、全局变量
3、malloc
static使用方便,但malloc更加灵活
char *fun()
{
static char str[] = "hello world";
return str;
}
int main()
{
char *p = fun();
puts(p);
return 0;
}
插入代码片
答案:随机值
出现问题的原因:str是局部的,fun函数结束,str生命周期就结束了
解决办法:延长生命周期
1、static
2、全局变量
3、malloc
static使用方便,但malloc更加灵活