本帖最后由 superbe 于 2019-9-12 08:48 编辑
freeLibrary函数有点问题,改过了,也加了注释。
# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
struct BOOK
{
char title[30]; //数据域 书名
char author[30]; //数据域 作者
struct BOOK *next; //指针域 (指向下一BOOK)
};
void getinput(struct BOOK* book) //获取输入
{
printf("请输入书名: ");
scanf("%s", book->title);
printf("请输入作者: ");
scanf("%s", book->author);
}
void addBook(struct BOOK **library) //library是一个二级指针
{ //*library是library指向的BOOK地址
//**library是这个BOOK地址保存的BOOK结构
//注意实参和形参名称相同,意义不同
struct BOOK* book , *temp;
book = (struct BOOK*)malloc(sizeof(struct BOOK));
if (book == NULL) //malloc函数返回NULL表示内存分配失败
{
printf("内存分配失败\n");
exit(1);
}
getinput(book); //为刚添加的BOOK结构输入信息(书名,作者)
if (*library != 0) //如果第一个BOOK地址有效(不为0),说明已经添加过第一本BOOK了
{ //那么在此BOOK前面继续添加一个BOOK,成为新的链表头
temp = *library;
*library = book;
book->next = temp;
}
else //否则,说明链表为空,那么新建一个BOOK
{
*library = book;
book->next = NULL;
}
}
void print(struct BOOK* library) //打印链表每个BOOK的信息(与添加的顺序相反)
{
struct BOOK* book;
int count = 1; //计数
book = library;
while (book != NULL)
{
printf("Book %d: \n", count);
printf("书名: %s\n", book->title);
printf("作者: %s\n", book->author);
book = book->next;
count++;
}
}
void freelibrary(struct BOOK* library) //这个函数有问题,已经修改过了
{
struct BOOK* temp;
while (library != NULL)
{
temp=library->next;
free(library);
//library = library->next; //问题就在这,上面library已经被free了怎么还能访问library->next呢
library=temp;
}
}
int main(void)
{
struct BOOK* library = NULL; //链表头指针,它里面保存的是第一个Book的地址
char ch;
while (1)
{
printf("请问是否需要录入书籍信息(y / n): ");
do
{
ch = getchar();
} while (ch != 'y' && ch != 'n');
if (ch == 'y')
{
addBook(&library); //传递的参数是library变量本身的地址
}
else
{
break;
}
}
printf("是否输出图书信息(y / n): ");
do
{
ch = getchar();
} while (ch != 'y' && ch != 'n');
if (ch == 'y')
{
print(library); //打印library指向的链表信息
}
freelibrary(library); //释放library指向的链表内存
return 0;
}
|