gpt4 book ai didi

c - 将变量传递给一个函数到另一个函数

转载 作者:太空宇宙 更新时间:2023-11-04 06:50:22 25 4
gpt4 key购买 nike

我试图从一个函数中获取 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

最佳答案

这个

   char userInput[MAX];

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

要么将其作为参数传入,要么使用 malloc 将其绑定(bind)到堆上。

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

还有 printf(userInput); 总是错误的

关于c - 将变量传递给一个函数到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52413358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com