假设有以下简单代码:
int main(void){
char *p;
int i = 1;
while(i){
char str[] = "string";
p = str;
i = 0;
}
/* Can I use above string by using `p` in here? */
return 0;
}
我将一个字符串(字符数组)声明为局部变量,仅在 while{}
中有效。但我将其数组地址保存到指针 p
中,该指针在 while{}
之外也有效。可以使用 p
在 while{}
之外使用字符串吗?
如果没问题,为什么会起作用?
最佳答案
Is it okay use the string outside
while{}
by usingp
?
否。在 while
的范围内,p
指向 str
的第一个字符。在 while
之外没有 str
,因此没有 p
指向的有效内存位置。
您可以通过在str
声明中使用static
存储类说明符来达到预期的效果
static char str[] = "string";
在 while
之外你可以使用 p
printf("%s\n", p);
这是因为在 block 中声明的static
变量在整个程序执行过程中驻留在相同的存储位置。
关于我可以在其范围之外使用声明为局部变量的数组值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29593087/