写出这个库程序,当我通过终端时,我收到了分段故障11。一开始调试它似乎位于结构的某个地方但是它给了我问题,我声明了我的FILE指针。有人可以对这件事情有所了解吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 40
#define MAX_BOOKS 1000
struct book
{
char title[MAX_LENGTH];
char author[MAX_LENGTH];
char subject[MAX_LENGTH];
}*Book;
struct library
{
struct book collection[MAX_BOOKS];
int num_books;
}*lib;
int main()
{
struct library *lib;
char title[MAX_LENGTH], author[MAX_LENGTH], subject[MAX_LENGTH];
Book = NULL;
lib->num_books = 0;
int events = 0, selection = 0;
FILE *ifp;
ifp = fopen("library.txt", "r");
if (ifp == NULL)
{
printf("\nFile not found\n");
exit(0);
}
fscanf(ifp, "%d", &events);
for (int i=0;i<events; i++)
{
Book = NULL;
fscanf(ifp, "%d", &selection);
switch (selection)
{
case 1:
fgets(title, MAX_LENGTH, ifp);
fgets(author, MAX_LENGTH, ifp);
fgets(subject, MAX_LENGTH, ifp);
strcpy(Book->title, title);
strcpy(Book->author, author);
strcpy(Book->subject, subject);
lib->num_books += 1;
//addBook(lib);
break;
case 2:
lib->num_books -= 1;
//deleteBook();
break;
case 3:
//search;
break;
case 4:
break;
case 5:
break;
default:
printf("Invalid command\n");
break;
}
}
fclose(ifp);
return 0;
}
答案 0 :(得分:2)
lib->num_books = 0;
这会产生问题。您尚未初始化lib
。
为其分配内存 -
lib=malloc(sizeof(struct library));
也不要忘记free
已分配的内存。
答案 1 :(得分:0)
1)错误在以下行中 lib-&gt; num_books = 0;
指针变量lib在没有初始化的情况下被引用。
2)还有一个错误是,您正在为读取操作“r”打开文件,但尝试将该文件用于写入操作。