Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 从函数返回的字符串未给出正确的输出_C_String - Fatal编程技术网

C 从函数返回的字符串未给出正确的输出

C 从函数返回的字符串未给出正确的输出,c,string,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);

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

我错过了什么?

在你的代码中,
chartmp[20]
是函数
readContactName()
的本地函数。一旦函数完成执行,就不存在
tmp
。因此,-
tmp
的地址也变得无效

因此,在
return
ing之后,在调用者中,如果您尝试使用
return
ed指针,(就像您在
updateContactName(contact,tmp);()
中所做的那样),它将调用

FWIW,
fflush(标准输入)也是UB
fflush()
仅为输出流定义

解决方案:

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

    • 在您的代码中,
      字符tmp[20]
      是函数
      readContactName()
      的本地函数。一旦函数完成执行,就不存在
      tmp
      。因此,-
      tmp
      的地址也变得无效

      因此,在
      return
      ing之后,在调用者中,如果您尝试使用
      return
      ed指针,(就像您在
      updateContactName(contact,tmp);()
      中所做的那样),它将调用

      FWIW,
      fflush(标准输入)也是UB
      fflush()
      仅为输出流定义

      解决方案:

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

      您不能在C中返回指向局部变量的指针。编译器允许您这样做,但不起作用。您不能在C中返回指向局部变量的指针。编译器允许您这样做,但不起作用。谢谢。。。这真的很有帮助!您是否已为此准备好模板?;-)我指的是答案本身…:-)谢谢这真的很有帮助!您是否已为此准备好模板?;-)我指的是答案本身…:-)