|
发表于 2020-2-21 21:52:44
|
显示全部楼层
传递**是因为,函数中实参变量和形参变量之间的数据传递是单向的“值传递”方式,如果只传递*library,那么将无法返回library链表。
但可以将代码修改如下,将add函数改为有返回值的指针函数:
#include <stdio.h>
#include <stdlib.h>
struct Book{
char title[128];
char author[40];
struct Book *next;
};
void getInput(struct Book *book)
{
printf("请输入书名:\n");
scanf("%s",book->title);
printf("请输入作者:\n");
scanf("%s",book->author);
}
struct Book * 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;
library->next=temp;
}else
{
library = book;
library->next=NULL;
printf("书名:%s\n",library->title);
printf("作者:%s\n",library->author);
}
return(library);
}
void printLibrary(struct Book *library)
{
int count=1;
while(library!=NULL)
{
printf("Book%d:\n",count);
printf("书名:%s\n",library->title);
printf("作者:%s\n",library->author);
library=library->next;
count++;
}
}
void releaseLibrary(struct Book *library)
{
struct Book *temp;
while(library != NULL)
{
temp=library;
library = library->next;
free(temp);
}
}
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')
{
library=addBook(library);
}else
{
break;
}
}
printf("请问是否需要打印图书信息:(Y/N)");
do{
ch=getchar();
}while(ch!='Y'&&ch!='N');
if(ch=='Y')
{
printLibrary(library);
}
releaseLibrary(library);
return 0;
}
|
|