#include <string.h>
#include <stdio.h>
char *in() {
char a[10];
scanf("%s",a);
return (a);
}
int main () {
char *a; a=in();
printf("\n%s",a);
return (0);
}
最佳答案
在您的代码中,
return (a);
尝试返回局部变量的地址。在调用方中,该地址的任何使用(尝试访问)都会导致 undefined behavior ,因为内存地址无效。
函数返回后,函数内部的局部变量将不复存在,其生存期到期。因此,与这些变量(对象)对应的地址变得无效。根据 C11
,第 §6.2.4 章
[...] If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
注意:也就是说,我个人的补充:: return
是一个关键字,请不要让它看起来像一个函数。
解决方案:您需要确保返回地址的变量的生命周期取代函数作用域,因此您可以
- 使用
malloc()
及其系列来分配内存 - 使用具有
静态
存储的变量。
关于无法通过函数返回值打印字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43392825/