将节点添加到链接列表覆盖

时间:2017-10-31 21:36:54

标签: c linked-list

我在学生链接列表中有一个链接列表,我正在尝试添加课程。但是,当我尝试添加课程时,它们只会相互覆盖。 到最后一个if()块工作的所有东西(所有课程信息的集合)。错误的地方是在第二个+时间通过循环插入新课程(所以&#34中的else {};否则如果(strcmp(arr [0],"}")= = 0){}"

else if (strcmp(arr[0], "    course") == 0)
{
    // Start making a course
    struct course cour;
    while (fgets(str, sizeof(str), fp))
    {
        str[strcspn(str, "\n")] = '\0'; // remove new line char from str
        token = strtok(str, " ");
        char *args[sizeof(str)];
        int i = 0;
        while (token) // Tokenize that shit
        {
            arr[i] = token;
            token = strtok(NULL, " ");
            i++;
        }
        if (strcmp(arr[0], "#") == 0)
        {
            // Do nothing, it's a comment
        }
        else if (strcmp(arr[0], "        grade") == 0)
        {
            char *course_grade = arr[2];
            cour.grade = course_grade[0];
        }
        else if (strcmp(arr[0], "        number") == 0)
        {
            char *course_num = arr[2];
            cour.number = atoi(course_num);
        }
        else if (strcmp(arr[0], "   }") == 0)
        {
            // Done making the course, add to list
            printf("We finished the course\n");
            if (stud.courses == NULL) // set as NULL when struct student stud is declared
            {
                // Since stud.courses == NULL, this must be the first course
                cour.next = NULL; // make the end of the list NULL
                stud.courses = &cour;
            }
            else
            {
                struct course *old = stud.courses->next; // old next course
                stud.courses->next = &cour; // set the next course as the one we just made
                cour.next = old; // replace the old next behind the new course
            }
            break;
        }
        else
        {
            printf("Nothing found :( \n");
        }
    }

1 个答案:

答案 0 :(得分:1)

我认为这一行存在一个问题:

struct course cour;

这意味着cour是一个局部变量,当你超出发布的代码时,它将超出范围(即不再存在)。因此,像在此处一样保存地址是个坏主意:

stud.courses = &cour;

在这里:

stud.courses->next = &cour;

我想你需要一个动态变量。像:

struct course *cour = malloc(sizeof *cour);

并更改所有

cour.

cour->

另一个问题是这些行

            struct course *old = stud.courses->next; // old next course
            stud.courses->next = &cour; // set the next course as the one we just made
            cour.next = old; // replace the old next behind the new course

他们应该是:

            cour->next = stud.courses;
            stud.courses = cour;