c - 使用 fgets() 的段错误

标签 c arrays fgets

我正在制作一个基本程序,并决定使用函数和指针,在第一个输入中我可以选择输入“厨房”或“楼上”,但是当我使用 fgets() 我遇到了段错误,不知道为什么。我试图打印出字符串以查看我是否得到了正确的输出,当然由于段错误它没有发生。

代码如下:

#include <stdio.h>
#include <string.h>
char one(char *oOne[]);
void two();
void three();

int main() {
    char *oOne[10], oTwo[10], oThree[10]; // Options one, two, and three.
    puts("WELCOME TO ASAD'S ADVENTURE");
    puts("");
    one(oOne);
    return 0;
}

char one(char *oOne[]) {
    puts("You are in a creepy house! Would you like to go \"upstairs\", or into the \"kitchen\"?");

    printf("\n> ");

    if (fgets(*oOne, sizeof *oOne, stdin) == NULL) { // Receiving the input from the user, and removing the \n caused by fgets().
        puts("EOF Occurred");
        return 1;
    }

    *oOne[strcspn(*oOne, "\n")] = 0;
    printf("%s\n", *oOne);
    // puts(*oOne);
}

这是我收到的输出:

WELCOME TO ASAD'S ADVENTURE

You are in a creepy house! Would you like to go "upstairs", or into the "kitchen"?

> kitchen
Segmentation fault

如何修复段错误?

最佳答案

C 中的字符串是指向字符的类型,例如:

char *oOne;

或者一个字符数组,如果你想静态分配你的内存:

char oOne[10];

但是不是一个指向字符数组的指针,这是你所拥有的:

char *oOne[10];

你需要:

char oOne[10];

然后:

one(oOne);

然后用适当的类型修改你的one函数:

char one(char *oOne)
{
    if (fgets(oOne, sizeof oOne, stdin) == NULL)
    {
            puts("EOF Occurred");
            return 1;
    }

    *(oOne + strcspn(oOne, "\n")) = 0;

    printf("%s\n", oOne);


}

虽然我会传入一个明确的长度,而不是使用 sizeof,因为这不适用于动态分配的字符串:

car one(char *oOne, int len)
{
    if (fgets(oOne, len, stdin) == NULL)
    {
            puts("EOF Occurred");
            return 1;
    }

    // etc...
}

关于c - 使用 fgets() 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32356895/

相关文章:

c# - 在 Visual Studio Proff 中调试 native 代码

c - 在 C 中,多线程,多个窗口调用一个窗口过程,每次调用都会使用新的局部变量还是我需要互斥体?

php - 多个数组的插入在空值上失败

c - 使用 fgets 从文件中读取

c - 使用互斥量的 pthread 同步

c - 如何计算 C 中格式字符串的参数数量?

arrays - 将项目移动到集合开头的最佳方法

Java Applet - ArrayIndexOutOfBoundsException(第 2 部分)

c - fgets 之后获取键盘输入

c - 分配给缓冲区时 fgets 泄漏