Char* 在不应该的时候显示 null

标签 c null scanf

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

identifierTemp 变量初始化为 NULL 但当用户输入他们想要的图书标识符时,identifierTemp 保持为 NULL?!?!

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

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)

最佳答案

你需要给 identifierTemp 一些内存,这样 scanf 就有地方放数据了

即改成

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

重新阅读scanf 的手册页,这样就不会超过限制

关于Char* 在不应该的时候显示 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28974184/

相关文章:

c - 为什么这个 C 程序的输出会卡住?

swift - 使 Optional.none 评估为 0

C: 使用 "scanf"读取一行其他字符中的 float

c - 使用 fscanf() 逐行读取文件,包括空格

c - 有什么方法可以判断文件描述符值已被重用?

c - For 循环不以空终止符终止

c++ - 多线程不利用多核?

java - Haskell 中的 undefined 和 Java 中的 null 有什么区别?

database - 如何建模或查询关系代数中不存在的东西

c - 使用 sscanf 从文件中读取