【问题标题】:Passing a variable to one function to another将变量传递给一个函数到另一个函数
【发布时间】:2018-09-19 19:57:29
【问题描述】:

我试图从一个函数中获取 userInput 而不是在另一个函数中使用它。当我在第一次输入字符时测试 char 是否在 DetermineWhatCommand 函数中工作时,我得到了错误的输出,但之后下一个输入的字符串会正确显示。

#include<stdio.h>
#include<string.h>
#define MAX 100




char * GetUserInput(){
  char userInput[MAX];
  fgets(userInput, sizeof (userInput), stdin);
  userInput[strcspn(userInput, "\n")] = '\0';

   return userInput;
}

void DetermineWhatCommand(char *userInput){
  printf(userInput);

}


int main() {

    char * userInput;
    userInput = new char[MAX];
    char exitTest[] = "exit";

    while(strcmp(exitTest, userInput) != 0){
        userInput = GetUserInput();
        DetermineWhatCommand(userInput);

   }
   return 0;
}

输出:

Hello    //First string entered
@        //What the output in the function looks like
Hello    //Second string entered
Hello    //What the output in the function looks like 

【问题讨论】:

标签: c string function


【解决方案1】:

这个

   char userInput[MAX];

在堆栈上 - 因此函数返回时超出范围。

要么将其作为参数传入,要么使用malloc 将其放入堆中。

顺便说一句:new 是 C++ - 如果使用 C++ 标记问题并使用std::string

还有printf(userInput);总是错的

【讨论】:

  • 我认为“结束它的生命周期”更好地表述为“超出范围”,因为范围是静态的。
【解决方案2】:

当您动态地使用内存时,它属于整个程序,而不是它被定义的范围。

在 OP 的代码中,一旦控制超出“静态”分配内存的函数范围,即函数 GetUserInput 的范围,内存就会被释放。

尽管在其中使用了new,但由于此问题已被标记为标签 C,因此我将展示您的 C 版本:

  char * GetUserInput()
  {
       char *userInput = malloc(MAX);
       //YOUR FUNCTIONALITY..........

       return userInput;
  } 

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多