繁体   English   中英

比较C中链表中的值时出现的问题

[英]Issue when comparing a value in a linked list in C

我正在用C语言编写一个“简单”程序,我们在其中创建一个链表,该链表的结构类似于电影,用于存储影片,标题,制作年份,评分(1-5)和指向该影片的指针。下一个节点。 我们不允许在此结构中添加任何内容或定义函数。

最重要的是,(出于某种原因)我们需要在main()的主体中编写整个链接列表,以便为该问题添加一定程度的意大利面条。 无论如何,在此程序中,我们应该让用户输入“ U”进行更新,或者输入“ S”进行电影搜索。 更新完成您所期望的,然后输入标题,年份,等级。 由此,我们应该将节点插入到链表的末尾

我们的搜索应循环访问此链接列表,如果找到匹配项,则应打印出电影,标题和年份。

尽管代码的更新部分有效,但似乎无法使搜索生效。 我正在使用一个名为temp的电影结构,该结构从头开始并遍历列表以尝试查找电影。 在通过printf运行了一些测试之后,我发现temp不管是什么,无论我输入什么电影,都只是一个空节点。

我假设这与我调用malloc的方式有关? 还是与未正确分配节点有关? 老实说,我不确定,很遗憾,实验室的TA也不知道D怎么了。

这是我的代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct movie_node {
        char title[250];
        int year;
        unsigned char rating;
        struct movie_node *next;
};

typedef struct movie_node movie;

int main() {

        // variables
        int loop = 1;
        movie *head = NULL; // represents first
        movie *current; // represents the last node
        movie *temp; // used for traversing the linked list
        head = malloc(sizeof(movie));
        int amountOfMovies = 0; // increment after each addition
        char choice; // either 'u' (update) or 's' (search)
        // ask user for input
        while(loop) {

                printf("%d Movie(s) in the database. Update or search (U/S): ", amountOfMovies);
                scanf(" %c", &choice);
                /* CHOICE 1, UPDATE */
                if(choice == 'U') {

                        // case 1, head is null, we must create a new node
                        if(head == NULL) {
                                // get input
                                printf("Name of the movie: ");
                                scanf(" %[^\n]%*c", head->title);
                                printf("Year: ");
          scanf("%d", &head->year);
                                printf("Rating: ");
                                scanf("%hhu", &head->rating);
                                head->next = NULL;
                                head = current; // set head to point to current
                        } else {
                                current = head;
                                // need to find where current is
                                while(current != NULL) {
                                        current = current->next;
                                } // end while
                                // current is now at the null position, indicating empty node
                                current = malloc(sizeof(movie)); // allocate mem
                                // get user input
                                printf("Name of the movie: ");
                                scanf(" %[^\n]%*c", current->title);
                                printf("Year: ");
                                scanf("%d", &current->year);
                                printf("Rating: ");
                                scanf("%hhu", &current->rating);
                                current->next = NULL;
                        } // end else
                        // output movie
                        printf("Movie \"%s\" is added to the database.\n", current->title);
                        amountOfMovies++; // increment amount of movies in database
                } else if(choice == 'S') {
                /* CHOICE 2, SEARCH */
                        // temp string
                        char tempTitle[250];
                        // flag to let us know if we found something
                        bool found = false;
                        // temp linked list to traverse
                        temp = head;
                        temp = malloc(sizeof(movie));
                        // ask user for input
                        printf("Name of movie: ");
                        scanf(" %[^\n]%*c", tempTitle);
                        printf("NAME OF MOVIE IN HEAD: %s\n", temp->title);             // test, take out later
                        while(temp != NULL) {
                                printf("NAME OF CURRENT MOVIE TO COMPARE TO: %s\n", temp->title); // test
                                if(strcmp(temp->title, tempTitle) == 0) {
                                        // match
                                        printf("Year: %d\n", temp->year);
                                        printf("Rating: %hhu\n", temp->rating);
                                        found = true;
                                        break;
                                } else { // no match so far
                                        temp = temp->next;
                                        printf("HAVEN'T FOUND MATCH, NEXT TITLE TO CHECK IS: %s\n", temp->title); // test print
                                        found = false;
                                }  // end else
                        } // end while
                        if(found == false) { // no match confirmed
                                printf("Movie \"%s\" does not exist in the database.\n", tempTitle);
                        }
                } else { // choice is invalid
                        loop = 0; // exit
                } // end if-else

        } // end while
        // free all the nodes

        return 0;
}

注意:我还没有实现的唯一事情就是释放内存。.我不确定百分百应该如何实现。

任何帮助是极大的赞赏..

问题出在您的malloc()调用上。 首先,您要做的是:

movie *head = NULL;
// ...
head = malloc(sizeof(movie));

这意味着head不再为null,您将无法以所需的方式插入第一部电影-将malloc()移动到其他位置。

其次,执行以下几行代码:

current = head; // <- this is OK
// ...
current = malloc(sizeof(movie)); // allocate mem <- this is NOT OK, for the same reason as before

同样,您可以像这样读取电影的标题: scanf("%249s", head->title)

如果您知道该怎么走,请告诉我。

除了代码中的问题外,还有另一个问题: 实验室的TA也不知道哪里出了问题

样品修复

movie *new_node(void){//aggregate the creation of a new node
    movie *node = malloc(sizeof(*node));//error check omit
    printf("Name of the movie: ");
    scanf(" %249[^\n]%*c", node->title);
    printf("Year: ");
    scanf("%d", &node->year);
    printf("Rating: ");
    scanf("%hhu", &node->rating);
    node->next = NULL;
    return node; 
}

int main() {
    int loop = 1;
    movie *head = NULL; 
    movie *current; 
    movie *temp; 
    //head = malloc(sizeof(movie));//"if(head == NULL) {" don't work 
    int amountOfMovies = 0; 
    char choice; 

    while(loop) {
        printf("%d Movie(s) in the database. Update or search (U/S): ", amountOfMovies);
        scanf(" %c", &choice);

        if(choice == 'U') {
            if(head == NULL) {
                current = head = new_node();//need set to current
            } else {
                current = head;
                while(current->next != NULL) {//"current != NULL" can't link
                    current = current->next;
                }
                current = current->next = new_node(); 
            } 
            printf("Movie \"%s\" is added to the database.\n", current->title);
            amountOfMovies++; 
        } else if(choice == 'S') {
            char tempTitle[250];
            bool found = false;//need <stdbool.h>
            temp = head;
            //temp = malloc(sizeof(movie));//Unnecessary
            printf("Name of movie: ");
            scanf(" %249[^\n]%*c", tempTitle);
            //printf("NAME OF MOVIE IN HEAD: %s\n", temp->title);            
            while(temp != NULL) {
                //printf("NAME OF CURRENT MOVIE TO COMPARE TO: %s\n", temp->title); 
                if(strcmp(temp->title, tempTitle) == 0) {
                    printf("Year: %d\n", temp->year);
                    printf("Rating: %hhu\n", temp->rating);
                    found = true;
                    break;
                } else { 
                    temp = temp->next;
                    printf("HAVEN'T FOUND MATCH, NEXT TITLE TO CHECK IS: %s\n", temp->title); 
                    //found = false;//Unnecessary
                }  
            } 
            if(found == false) { 
                printf("Movie \"%s\" does not exist in the database.\n", tempTitle);
            }
        } else { 
            loop = 0; 
        } 
    } 
    // free all the nodes
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM