我是链表主题的新手,我刚刚使用链表创建了我的第一个程序,问题是它没有将任何数据保存到结构中。它运行良好,没有错误,但是打印时不显示任何数据。这是我的代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
int nID;
char chTitle;
struct node* next;
};
void addList(struct node *head);
void printList(struct node *head);
int checkID(struct node *head, int t);
int main(int argc, const char * argv[])
{
int nInput;
struct node *head = NULL;
while (1)
{
printf("ntt~~MENU~~n");
printf("1. Add a new bookn");
printf("2. Print all datan");
printf("3. Exitn");
printf("Make your selection: ");
scanf("%d", &nInput);
switch (nInput)
{
case 1:
addList(head);
break;
case 2:
printList(head);
break;
case 3:
printf("nGoodby!!! Thanks for using the programn");
exit(1);
break;
default:
printf("ntt~~Invalid Input~~n");
break;
}
}
return 0;
}
void addList(struct node *head)
{
int bookId; // Used to store the BOOK ISBN so it can be checked if it already exist
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
printf("n Enter Book Detailsn");
printf("Enter book ISBN: ");
scanf("%d", &bookId);
int bInd = checkID(head, bookId);
if (bInd == 0)
{
printf("Enter title: ");
scanf("%s", &temp->chTitle);
temp->next = head;
head = temp;
}
else
{
printf("nSorry another book using that id!n" );
}
}
void printList(struct node* head)
{
while (head != NULL)
{
printf("%s", &head->chTitle);
head = head->next;
}
}
int checkID(struct node *head, int t)
{
head = NULL;
while (head != NULL)
{
if (head->nID == t)
return 1;
head = head->next;
}
return 0;
}
一个问题就在这里:
void addList(struct node *head)
addList()
正在获取头部指针的副本,因此当您在此函数中修改它时,您只是在修改该本地副本。不会修改调用方的版本。解决此问题的一种方法是使用双指针:
void addList(struct node **head)
{
int bookId; // Used to store the BOOK ISBN so it can be checked if it already exist
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
printf("n Enter Book Detailsn");
printf("Enter book ISBN: ");
scanf("%d", &bookId);
int bInd = checkID(*head, bookId);
if (bInd == 0)
{
printf("Enter title: ");
scanf("%s", &temp->chTitle);
temp->next = *head;
*head = temp;
}
else
{
printf("nSorry another book using that id!n" );
}
}
然后,您的来电者也必须更改:
addList(&head);
此外,正如@5gon12eder提到的,char
只包含一个字符。您需要一个char
数组来保存您的标题:
struct node {
int nID;
char chTitle[100]; /* or how ever long your title can be */
struct node* next;
};
你可以像这样更改你的addList标题,
void addList(struct node *&head)
在这里,head 成为对节点类型指针的引用。因此,当您在 addList 中修改head
时,它将反映回原始列表中。