我的代码是:
#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*
为什么会有奇怪的未知字符返回到控制台而不是“测试”?
最佳答案
这是因为您正在返回局部变量的值。尝试把这个:
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/