Char *在不应该显示时显示为null

时间:2015-03-10 21:14:04

标签: c null scanf

在我为书籍数据库程序编写的这个函数中,我让用户输入书籍标识符,然后它应该去搜索该书的链表并显示它的详细信息。

identifierTemp 变量初始化为 NULL ,但当用户输入所需书籍的标识符时, identifierTemp 仍为 NULL < / em>的?!?!

这是功能。希望有人能发现我的错误。提前谢谢。

void viewBook() {

    printf("\n*** VIEW A BOOK ***\n");

    struct node *currentBook, *prevBook;

    bool notFound = true;

    char* identifierTemp = NULL;

    //user input
    printf("\nBook Identifier: ");
    scanf("%s", identifierTemp);
    fflush(stdin);

    printf("\n");

    if (isEmpty())
        printf("Error - there are no books in the list\n\n\n");
    else  {
        currentBook = prevBook = firstBook;

        while (notFound && currentBook != NULL) {

            if (identifierTemp == currentBook->element->identifier)
                notFound = false;
            else {
                    prevBook = currentBook;
                    currentBook = currentBook->next;
            }//end else

        } //end while

        if (notFound)
            printf("Error - there is not such book with the identifier %s\n\n\n", identifierTemp);

        else  {

            //DISPLAY ALL BOOK DETAILS
            printf("\n\nIdentifier: %s", currentBook->element->identifier);
            printf("\nTitle: %s", currentBook->element->title);
            printf("\nAuthor: %s", currentBook->element->author);
            printf("\nYear: %d", currentBook->element->year);
            printf("\nStatus (1 = not available to take out): %d", currentBook->element->status);
            printf("\nCustomer: %s", currentBook->element->customer);
            printf("\nTimes Taken Out: %d", currentBook->element->timesTakenOut);
            printf("\nGenre: %s", currentBook->element->genre);
            } //end else

            printf("\n");

       }//end else

    menuSystem();//return to the menu

}//end ViewBook

控制台输出:

*** VIEW A BOOK ***

Book Identifier: *USER INPUT HERE*

Error - there is no such book with the identifier (null)

2 个答案:

答案 0 :(得分:3)

您需要为identifierTemp提供一些内存,以便scanf可以放置数据

即。将其更改为

char identifierTemp[4096]; // Or some other size that can reasonably store the string.

重新阅读scanf上的手册页,以便不会超出限制

答案 1 :(得分:1)

identifierTemp正确分配内存后,还需要正确比较字符串。这段代码:

identifierTemp == currentBook->element->identifier

比较字符串地址(指针)并且永远不会成立。您需要使用strcmp

if (strcmp(identifierTemp, currentBook->element->identifier) == 0)
    notFound = false;

顺便说一句,双重否定有点令人反感。为什么不让布尔值Found = false开始,然后在找到它时设置Found = true