#include<stdio.h>
extern char * stri();
int main(void)
{
char *p = stri();
printf("%s\n", p);
return 0;
}
char * stri()
{
char arr[] = "hello world";
return arr;
}
这样输出的是乱码。
#include<stdio.h>
extern char * stri();
int main(void)
{
char *p = stri();
printf("%s\n", p);
return 0;
}
char * stri()
{
char *arr = "hello world";
return arr;
}
这样输出的是hello world
为什么呢?字符串常量的生命周期不是整个程序的生命周期吗?为什么第一个不行。(刚学C语言不太懂,求大佬解答)。。。。。
第一个是局部的数组,存放在栈中,函数中执行完了之后内存就释放,只有全局的数组才是整个程序的生命周期的。第二个是字符串常量,字符串常量存放在数据段中,是整个程序运行周期都是存在的,而且不能修改其中的值。可以看看这个https://blog.csdn.net/qq_28249373/article/details/76768776
第一个代码我编译报错:function returns address of local variable。意思是:函数返回局部变量的地址。