一道道面试 小试题

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更加灵活

猜你喜欢

转载自blog.csdn.net/qq_43967317/article/details/107499582