【发布时间】:2015-09-03 00:53:28
【问题描述】:
我正在制作一个基本程序,并决定在第一个输入中使用函数和指针,我可以选择键入“厨房”或“楼上”,但是当我使用 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
如何解决分段错误?
【问题讨论】:
-
您是否尝试通过
gdb或valgrind运行此程序? -
你有一个
char*(oOne) 的数组,这是一个尚未初始化的指针数组。您需要为它们分配内存。您还需要仔细检查sizeof *oOne为您提供的内容。 -
另外,"sizeof *oOne" 将返回指针的大小(4 或 8 字节),而不是您传入的缓冲区大小。您需要将缓冲区大小作为参数传入到函数。