为什么这里会出现死循环? (链表打印)

Why is there an infinite loop here? (linked list printing)

我正在用链表做一些练习,这些是结构。

typedef struct roomList roomList;
typedef struct school school;
typedef struct studentList studentList;
roomList *getRoom(school* school, int class, int roomNr);

struct studentList{

    char *name;
    int class; 
    float grade;
    int roomNr;
    studentList *next;
    studentList *prev;
};


struct roomList{

    int nrOfStudents;
    int roomNr;
    studentList *students; //pointer to student list.
    roomList *next;
    roomList *prev; 
};



struct school{

    int totalStudents;
    roomList *Class[13]; //array of classes, each index contains rooms.
};

这是无限循环发生的地方,它是一个打印房间内所有学生的函数。

void printRoom(school *school, int class, int roomNr)
{
    roomList *room = getRoom(school, class, roomNr);
    studentList *student;

    if(room != NULL)
    {
        int i = 1;
        printf("Nr of students: %d\n", room->nrOfStudents);
        while(room->nrOfStudents != 0 && student != NULL)
        {
            student = room->students;
            printf("%d - \"%s\" ",i, student->name);
            student = student->next;
            i++;
        }
    }   
}

这就是我创建 student

的方式
studentList *createStudent(int class, char *name, int roomNr)
{
    studentList *newNode;
    newNode = (studentList*)calloc(1, sizeof(studentList));
    newNode->class  = class;
    newNode->name   = (char*)malloc(strlen(name)+1);
    strcpy(newNode->name, name);
    newNode->roomNr = roomNr;
    newNode->grade  = 0;
    newNode->next   = newNode->prev = NULL;

    return newNode;
}

最后,这就是我将 student 插入 room 的方式。

void insertStudentToRoom(school* school, int class, int roomNr, char *name)
{
    roomList *room;
    room = getRoom(school, class, roomNr);
    studentList *newStudent;
    newStudent = createStudent(class, name, roomNr);

    if(room->students != NULL)
    {
        newStudent->next = room->students;
        room->students->prev = newStudent;
        room->students = newStudent;
        room->nrOfStudents++;
        school->totalStudents++;
    }
    else
    {
        room->students = newStudent;
        room->nrOfStudents++;
        school->totalStudents++;
    }
}

只有当我将多个 student 插入 room 时才会发生无限无限循环,并且当只有一个学生时退出正常,我已经尝试为我的退出条件摸索while() 无济于事。

    while(room->nrOfStudents != 0 && student != NULL)
    {
        student = room->students;
        printf("%d - \"%s\" ",i, student->name);
        student = student->next;
        i++;
    }

仔细看。您永远不会在循环中更改 room 。所以 student = room->students; 将在循环中每次都为 student 设置完全相同的值。如果第一次没坏,以后就不会坏了。

您可能希望 student = room->students; 脱离循环。你只想指着房间里的第一个学生一次。