我正在尝试使用c将一个链表添加到另一个链表中。问题是程序正在进入一个无限循环,我不知道为什么。下面是c代码
typedef struct bookInfo
{
int code;
struct bookInfo *next;
} bookInfo;
typedef struct subscriber
{
int code;
struct bookInfo *books;
struct subscriber *next;
struct subscriber *prec;
} subscriber;
typedef bookInfo *Book;
typedef subscriber *Subscriber;
typedef Subscriber *SubscriberList;
void newBook(Book *bk, int val)
{
bookInfo *new_node = malloc(sizeof(bookInfo));
bookInfo *last = *bk;
new_node->code = val;
new_node->next = NULL;
if (*bk == NULL)
{
*bk = new_node;
}
else
{
while (last->next != NULL)
last = last->next;
last->next = new_node;
}
}
Subscriber Add_book(Subscriber S, Book Bk)
{
bookInfo *newNode = malloc(sizeof(bookInfo));
bookInfo *tmp;
newNode->next = NULL;
newNode->code = Bk->code;
if (S == NULL)
printf("nl'abonnee est nulle");
else
{
if (S->books == NULL)
S->books = newNode;
else
{
tmp = S->books;
while (tmp != NULL)
tmp = tmp->next;
tmp->next = newNode;
printf("nl'ajout du livre a ete effectue");
};
}
return S;
};
希望你们能帮助我,谢谢你们。我不知道函数newBook中的问题是什么,这里是我的主要函数
int main()
{
book_ref, sub_ref = NULL;
newSubscriber(&sub_ref);
bookInfo b1 = {20,NULL};
Add_book(sub_ref, &b1);
printf("n%d : %d", sub_ref->code, sub_ref->books->code);
}
在您的代码中,
while (tmp != NULL) tmp = tmp->next;
当这个循环结束时,tmp为NULL,所以下一行将尝试访问NULL指针。
您应该将其更正为,while(tmp->next != NULL)
为了删除无限循环,我所要做的就是将订阅者结构中的书籍指针定义为NULL
void newBook(Book *bk, int val)
{
bookInfo *new_node = malloc(sizeof(bookInfo));
bookInfo *last = *bk;
new_node->code = val;
new_node->next = NULL;
new_node->books = NULL;
if (*bk == NULL)
{
*bk = new_node;
}
else
{
while (last->next != NULL)
last = last->next;
last->next = new_node;
}
}
Subscriber Add_book(Subscriber S, Book Bk)
{
bookInfo *newNode = malloc(sizeof(bookInfo));
bookInfo *tmp;
newNode->next = NULL;
newNode->code = Bk->code;
newNode->books = NULL;
if (S == NULL)
printf("nl'abonnee est nulle");
else
{
if (S->books == NULL)
S->books = newNode;
else
{
tmp = S->books;
while (tmp != NULL)
tmp = tmp->next;
tmp->next = newNode;
printf("nl'ajout du livre a ete effectue");
};
}
return S;
};
一切顺利。