无法通过函数返回值打印字符串?

标签 c string printf return-value function-calls

#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/

相关文章:

c++ - ']' 标记之前的预期表达式? C

arrays - 在 Ruby 中,如何在给定要分解字符串的索引数组的情况下分解字符串?

javascript - 传递带有连字符的字符串被评估为整数(减法!)js

c++ - 设置精度和裁剪尾随零但从不打印指数

c - 在翻译单元中使用 extern

c - 显示打印运行时错误

android - 如何从 ListView 项中获取特定字符串

java - 如何让 printf %x 类似于 python

c - 在 C 中打印结构体的名称

c - 将数字字符串汇编成 int