我正在制作一个基本程序,并决定使用函数和指针,在第一个输入中我可以选择输入“厨房”或“楼上”,但是当我使用 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/