我的代码是:
#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/