【问题标题】:Returning string from function is not giving proper output [duplicate]从函数返回字符串没有给出正确的输出[重复]
【发布时间】:2015-08-31 11:41:19
【问题描述】:

我正在尝试创建一个函数,该函数将从用户那里接收 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
}

我错过了什么?

【问题讨论】:

  • 你不能在 C 中返回指向局部变量的指针。编译器允许你这样做,但它不起作用。

标签: c string


【解决方案1】:

在您的代码中,char tmp[20]; 是函数 readContactName() 的本地函数。一旦函数执行完毕,tmp 就不存在了。所以,tmp的地址也失效了。

所以,在returning 之后,在调用者中,如果您尝试使用returned 指针,(就像您在updateContactName(contact, tmp);() 中所做的那样)它将调用@987654321 @。

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

解决方案:

  • tmp 定义为指针。
  • 动态分配内存(使用malloc() 或family)。
  • 使用完分配的内存后,您还需要free() 它。

【讨论】:

  • 谢谢...真的很有帮助!
  • 您是否已经为此准备了模板? ;-)
  • 我指的是答案本身...... :-)
猜你喜欢
  • 2020-05-06
  • 2013-07-30
  • 1970-01-01
  • 2012-08-07
  • 1970-01-01
  • 2013-05-11
  • 2021-10-07
  • 2023-01-22
  • 2018-01-23
相关资源
最近更新 更多