gpt4 book ai didi

c - 尝试通过指针返回 char 数组,但给出了不正确的结果

转载 作者:行者123 更新时间:2023-12-02 15:16:30 25 4
gpt4 key购买 nike

我的代码是:

#include <stdio.h>
#include <string.h>
char *getUserInput() {
char command[65];

//Ask the user for valid input
printf("Please enter a command:\n");
fgets(command, 65, stdin);

//Remove newline
command[strcspn(command, "\n")] = 0;
return command;
}

int main() {
char *recCommand = getUserInput();
printf("%s", recCommand);
return 0;
}

执行此代码时,这是控制台:

Please enter a command:
Test <-- this is the command I entered
*weird unknown characters returned to console*

为什么有奇怪的未知字符返回到控制台而不是“Test”?

最佳答案

这是因为您正在返回局部变量的值。尝试这样写:

char *getUserInput() {
static char command[65];

//Ask the user for valid input
printf("Please enter a command:\n");
fgets(command, 65, stdin);

//Remove newline
command[strcspn(command, "\n")] = 0;
return command;
}

关于c - 尝试通过指针返回 char 数组,但给出了不正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29552702/

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