在vscode上运行出现段错误,不知道为啥,数据录入后输出失败,求帮忙改一下,并说明一下原因,感谢。
#include<stdio.h>
#include<windows.h>
//头插法建立单链表
struct Book
{
char title[128];
char author[40];
struct Book *next;
};
void getInput(struct Book *book)
{
printf("please input the title:\n");
scanf("%s",book->title);
printf("please input the author:\n");
scanf("%s",book->author);
}
void addBook(struct Book **library)
{
struct Book *book,*temp;
book = (struct Book *)malloc(sizeof(struct Book));
if(book == NULL)
{
printf("failed to apply for space");
exit(1);
}
getInput(book);
if(*library!=NULL)
{
temp = *library;
*library = book;
book->next = temp;
}
else{
//如果是空的单链表,那么就把library指向新的节点
*library = book;
book->next = NULL;
}
};
void printLibrary(struct Book *library)
{
struct Book *book;
int count =1;
while(book->next !=NULL)
{
printf("Book%d",count);
printf("Book_title:\n",book->title);
printf("Book_author\n",book->author);
book = book->next;
count++;
}
}
void releaseLibrary(struct Book *library)
{
while (library!=NULL)
{
/* code */
free(library);
}
}
int main()
{
int ch;
struct Book *library = NULL;
while(1)
{
printf("if you input the message of book?(Y/N)");
do
{
/* code */
ch =getchar();
} while (ch!='Y'&&ch!='N');
if(ch=='Y')
{
addBook(&library);
}
else{
break;
}
}
printf("If you print the message of book?(Y/N)");
do
{
ch = getchar();
}while(ch!='Y'&&ch!='N');
if(ch == 'Y')
{
printLibrary(library);
}
system("pause'");
}