[英]Why and how returning the address of a static variable is OK while doing the same with non-static variable gives wrong result?
char str[] = "hello";
这个定义不起作用,但是
static char str[] = "hello"
这行得通,为什么呢?
完整代码:
char *retstr(void)
{
char str[] = "hello"; //This definition dosnt work
return str;
}
int main()
{
printf("\n%s\n",retstr());
return 0;
}
的情况下
char str[] = "hello"; //This definition dosnt work
您正在尝试返回局部变量str
的地址。 这里使用返回值是未定义的行为 ,因为一旦retstr()
函数完成执行,就不会存在str
变量。
太太
static char str[] = "hello";
之所以有效,是因为static
变量作为static storage duration 。 它的生命周期是程序的整个执行过程。 因此,即使在retstr()
函数完成执行后, str
仍然有效,因此返回值有效。
相关: C11
,第§6.2.4章, 对象的存储时间 ,第3段
......与存储类说明
static
,具有静态存储时间 。 它的生命周期是程序的整个执行过程,并且在程序启动之前,它的存储值仅初始化一次。
char str[] = "hello"; //This definition dosnt work
return str;
在这里,您将返回本地地址。 这就是为什么它不起作用
static char str[] = "hello"
在此过程中,您正在将'str'变量的范围更改为整个程序。 这就是为什么它起作用。
您不能从函数返回局部变量。 局部变量存在于堆栈中,一旦函数完成,该堆栈空间将被释放,并可由下一个函数调用使用。
char str[] = "hello"; //this won't work as it is a local variable
一旦超出范围,就不会再有其他函数调用名为str
变量。
但是static
变量的生存期遍及整个程序。
static char str[] = "hello"; //this will work
因此,在使用static
它不会给出任何错误。
静态变量仅创建一次,并且在函数返回时不会被销毁,而局部变量在函数结束时会被销毁。
每次调用函数时都会创建局部变量,并在返回时销毁该局部变量。
如果是局部变量:您将返回一个指针,该指针不再存在。
如果是全局变量:字符串仍然存在,因此它将始终有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.