问题一: 声明放最前面,告诉编译器有这个东西。编程的良好习惯。声明和定义放一起,而且已经在main前,要声明何用?
问题二:看代码
问题三:释放内存问题,自己琢磨
#include <stdio.h>
#include <stdlib.h>
struct Book
{
char title[128];
struct Book *next;
};
void getinput(struct Book *book);
void addbook(struct Book **lib);
void printbook(struct Book *lib);
void freebook(struct Book *lib);
int main(void)
{
struct Book *lib;
lib = NULL; // 初始化NULL
addbook(&lib);
printbook(lib);
freebook(lib);
return 0;
}
void getinput(struct Book *book)
{
printf("please input the title\n");
scanf("%s",book->title);
}
void addbook(struct Book **lib)
{
struct Book *book, *tem;
char ch;
// 循环输入
while(1)
{
book=(struct Book *)malloc(sizeof(struct Book));
printf("shi fou shu ru information y/n\n");
do
{
ch=getchar();
}while(ch!='y' && ch!='n');
if(ch=='y')
{
getinput(book);
}
else
{
break;
}
if(*lib==NULL) // 问题1:赋值 = ; 判断是否相等 ==, 问题2:初始化时你没有lib = NULL 这里何时才会=NULL?
{
*lib=book;
book->next=NULL;
}
else
{
tem=*lib;
*lib=book;
book->next=tem;
}
}
}
void printbook(struct Book *lib)
{
struct Book *book;
int count=1;
book=lib;
while(book!=NULL)
{
printf("book%d de title is %s\n",count,book->title);
book=book->next;
count++;
}
}
void freebook(struct Book *lib)
{
lib=lib->next;
free(lib);
}
|