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

标签 c arrays pointers

我的代码是:

#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/

相关文章:

C运算符+=序列点?

c++ - 查找由智能指针引起的内存泄漏

c - 功能性能测试

c - C中具有大量字符的字节顺序

javascript - Jquery 无法访问循环外的数组

javascript - 为什么带有数组的 'for(var item in list)' 在 JavaScript 中被认为是不好的做法?

c++ - 我很难将我的一些代码从 main 移动到函数

c - 我的搜索功能无法正常工作,因为我的 if 语句有问题,并且我正在使用链表

c++ - 外部库中出现奇怪的 C2065 错误

java - 使用正则表达式解析数组语法