【问题标题】:C: Adding data to structure using linked listC:使用链表将数据添加到结构中
【发布时间】:2015-02-06 19:52:26
【问题描述】:

我是 c 新手,正在学习链表,我决定创建一个图书馆管理器来使用链表管理我的书籍,但它似乎没有使用链表将数据保存到结构中。当有人试图添加一本新书时,该函数会点击 checkID 函数来查看具有相同 id 的书是否已经存在,但是当我执行显示信息时,结构中似乎没有任何内容。

void addBook()
{
    int bookId;
    BOOK *head = NULL, *temp;
    temp = (BOOK*) malloc(sizeof(BOOK));

    printf("\n Enter Book Details\n");
    printf("Enter book ISBN: ");
    scanf("%d", &bookId);
    int bInd = checkID(bookId);
    if (bInd == 0)
    {
        printf("Enter book title: ");
        scanf("%s", &temp->chTitle);
        printf("Enter book type (eg. magazine, novel): ");
        scanf("%s", &temp->chType);
        printf("Enter book publisher (eg. UTA): ");
        scanf("%s", &temp->chPublisher);
        printf("Enter book's number of pages: ");
        scanf("%d", &temp->nPages);
        printf("Enter book's price: ");
        scanf("%f", &temp->nPrice);
        printf("Enter year published: ");
        scanf("%d", &temp->nPubYear);
        //temp->next=NULL;
        if (head == NULL)
        {
            head = temp;
            temp->next = NULL;
        }
        else{
            temp->next = head;
            head = temp;
        }
        //BOOK[count].nStatus = IN;
        count++;
    }
    else
    {
        printf("\nSorry another book with that id: Try again!\n" );
        addBookFunction();
    }
}

int checkID(int t)
{
    BOOK *head;
    while (head != NULL)
    {
        if (head->nID == t)
            return 1;
        head = head->next;
    }
    return 0;
}

【问题讨论】:

  • head 已被请求它是一个全局变量。

标签: c linked-list


【解决方案1】:

别担心!这是正常的 !每次添加一本书时,您都在创建一个新的书库! :)

在您的位置,解决此问题的一种简单方法是将您的“图书馆藏书”传递给您的 AddBook 方法:

void addBook(BOOK *libraryBooks)
int checkID(BOOK *libraryBooks, int t)

然后删除你的变量声明'head'。将所有 'head' 更改为 'libraryBooks' 并将变量传递给 checkID。

在此功能之上,您必须管理您的图书馆。

【讨论】:

    【解决方案2】:

    checkID()addBook() 应该都接受链表的头部作为附加参数。遍历checkID() 中的链表的head 指针看起来像是在用适当的值初始化之前就被使用了。您还没有遇到空指针异常可能只是幸运的巧合。

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多