单链表课程 ,为什么没有为library申请内存却要释放它,申请了的却不释放
#include <stdio.h>#include <stdlib.h>
struct Book
{
char title;
char author;
struct Book *next;
};
void getInput(struct Book *book);
void addBook(struct Book **library);
void printLibrary(struct Book *library);
void releaseLibrary(struct Book *library);
void getInput(struct Book *book)
{
printf("请输入书名");
scanf("%s", book->title);
printf("请输入作者");
scanf("%s", book->author);
}
void addBook(struct Book **library)
{
struct Book *book, *temp;
book = (struct Book *)malloc(sizeof(struct Book));
if (book == NULL)
{
printf("内存分布失败\n");
exit(1);
}
getInput(book);
if (*library != NULL)
{
temp = *library;
*library = book;
book->next = temp;
}
else
{
*library = book;
book->next = NULL;
}
}
void printLibrary(struct Book *library)
{
struct Book *book;
int count = 1;
book = library;
while (book != NULL)
{
printf("Book%d: ", count);
printf("书名: %s\n", book->title);
printf("作者:%s\n", book->author);
book = book->next;
count++;
}
}
void releaseLibrary(struct Book *library)
{
while (library != NULL)
{
free(library);
library = library->next;
}
}
int main(void)
{
struct Book *library = NULL;
int ch;
while (1)
{
printf("是否录入书籍信息(Y/N)");
do
{
ch = getchar();
} while (ch != 'Y' && ch != 'N');
if (ch == 'Y')
{
addBook(&library);
}
else
{
break;
}
}
printf("是否打印书籍信息(Y/N)");
do
{
ch = getchar();
} while (ch != 'Y' && ch != 'N');
if (ch == 'Y')
{
printLibrary(library);
}
releaseLibrary(library);
return 0;
} 可以说清楚点吗把具体代码 几行给说一下 int main(void)
{
struct Book *library = NULL; library 是一个Book类型的指针变量,没有分配内存。
int ch;
void addBook(struct Book **library)
{
struct Book *book, *temp;
book = (struct Book *)malloc(sizeof(struct Book)); book 分布了内存空间,
if (book == NULL)
{
printf("内存分布失败\n");
exit(1);
}
void releaseLibrary(struct Book *library)
{
while (library != NULL)
{
free(library); 在结束程序时却把library内存释放了,library好像没有分配内存。
library = library->next;
}
}
library是链表头指针。在addBook函数里,将每个book加入到链表中,在releaseLibrary函数中用循环将链表中所有book都释放掉了。
另外,releaseLibrary这个函数有点问题,先free(library),再访问library->next有问题。 建议再在releaseLibrary这个函数里引入第二个指针来处理释放问题,一个指针做不到的。
页:
[1]