Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
试图通过指针返回char数组,它';它给出了错误的结果_C_Arrays_Pointers - Fatal编程技术网

试图通过指针返回char数组,它';它给出了错误的结果

试图通过指针返回char数组,它';它给出了错误的结果,c,arrays,pointers,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[strcs

我的代码是:

#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;
}
#包括
#包括
char*getUserInput(){
char命令[65];
//要求用户提供有效的输入
printf(“请输入命令:\n”);
fgets(命令,65,标准输入法);
//删除换行符
命令[strcspn(命令,“\n”)]=0;
返回命令;
}
int main(){
char*recCommand=getUserInput();
printf(“%s”,recCommand);
返回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;
}

在做了更多的研究之后,似乎最好的方法是从存储getUserInput输入的主函数中实际传入一个char数组

这是我修改后的代码:

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

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

int main {
    char recCommand[65];
    getUserInput(recCommand);
    printf("%s", recCommand);
    return 0;
}

退出函数作用域时,局部变量被禁用。因此,我应该返回char数组命令本身,而不是返回指向“command”的指针?请尝试返回strdup(command)这个复制字符串。(保护堆中的区域),然后
释放(命令)在main。为什么我们需要释放(命令)?您在这里指的是位于getUserInput作用域内还是主作用域内的命令?堆的区域没有释放,它仍然是安全的。因此用户必须被释放。我来自C#背景,是否可以从getUserInput函数返回command的值?@AdamNygate:是的,可能。但分配内存需要一些工作,然后确保及时释放内存。在C语言中,这可能是最好的选择。问题是,如果调用
getUserInput()
两次,第二个值将覆盖第一个值。这可能会导致多线程程序出现问题,其中多个线程调用函数,也可能会导致单线程程序出现问题,在使用第一次调用的返回值之前调用函数两次。将数组长度硬编码到函数中是一个坏主意。至少使其
void getUserInput(char*命令,size\u t size)
或类似。我已将长度设置为宏并在commonmacros.h文件中定义,请求的输入将始终为65个字符长(64+\0)