c - 从函数返回字符串没有给出正确的输出

标签 c string

<分区>

我正在尝试创建一个函数,它将从用户那里接收一个 char * 并将其打印出来。

当我打印它时,它把我的值变成了一些奇怪的东西。

**//input method**

char* readContactName(){
    char tmp[20];
    do{
    printf("What is your contact name?: (max %d chars) ", MAX_LENGH);
    fflush(stdin);
    scanf("%s", &tmp);
    } while (!strcmp(tmp, ""));

    return tmp;
}

void readContact (Contact* contact) 
{

    char* tmp;

    tmp = readContactName();
    updateContactName(contact, tmp);
}

**//when entering this function the string is correct**
void updateContactName(Contact* contact, char str[MAX_LENGH])
{
    printf("contact name is %s\n",&str);  --> prints rubish
}

我在这里错过了什么?

最佳答案

在您的代码中,char tmp[20]; 是函数 readContactName() 的局部变量。一旦函数执行完毕,tmp 就不存在了。因此,tmp 的地址也变得无效。

因此,在 returning 之后,在调用方中,如果您尝试使用 returned 指针,(就像您在 updateContactName(contact, tmp);()) 它将调用 undefined behaviour .

FWIW,fflush(stdin); 也是 UB。 fflush() 仅为输出流定义。

解决方法:

  • tmp 定义为指针。
  • 动态分配内存(使用 malloc() 或系列)。
  • 一旦你使用完分配的内存,你需要free()也是。

关于c - 从函数返回字符串没有给出正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32310400/

相关文章:

c - 指针操作、内存扫描

c - 函数指针处理程序

c - 有没有 Hello World 堆溢出的例子?

python - 通过使用 try-except block 编写一小段代码来汇总字符串中的数字

c - C语言如何给链表的每个节点添加描述

c++ - C/C++ 中的地址偏移量是否在编译时解析?

ruby - 如何在不转换为不同编码的情况下替换 Ruby 中的 UTF-8 错误?

java - 删除空字符串并减少相同的 String[][] 数组

c# - 在 C# 中将字符串数组转换为 float 组

C++:将字符串转换为 vector <double>