似乎在我的代码中,我有一个无限循环打印出同一个名为 search 的 class_t 变量,尽管试图将变量向前移动到下一个 class_t。所有 class_t 结构要么指向 (class_t*)0(因为如果我使用 NULL 会收到编译器警告,因为我在比较 class_t* 和 void*),或者指向下一个适当的 class_t 结构。我做错了什么,或者我应该在其他地方寻找我的问题吗?
class_t *search = (students + i)->class_p;//students is a seperate structure where class_p is a pointer to a class_t structure
while(search != (class_t*)0)
{
fprintf(output,": %s%d %d %d\n", search->name, search->number, search->section, search->credits);
search = search->nextClass;
}
这是输出的示例,查看它,它是文件中 class_t 中的最后一次读取
: CS521 1 4
: CS521 1 4
: CS521 1 4
: CS521 1 4
: CS521 1 4
: CS521 1 4
: CS521 1 4
: CS521 1 4
: CS521 1 4
: CS521 1 4
: CS521 1 4
: CS521 1 4
这是 class_t 的创建:
class_t newClass;
newClass.number = classid;
newClass.section = section;
newClass.credits = credits;
newClass.nextClass = (class_t*)0;
添加节点时:
void addNode(student_t students[], class_t addClass, int ref)
{
int found = 0;
if((students + ref)->class_p == (class_t*)0)//no classes yet
{
(students + ref)->class_p = &addClass;
found = 1;
}
else if((*((students + ref)->class_p)).number > addClass.number && found == 0)//checks first class
{
class_t *temp = (students + ref)->class_p;
(students + ref)->class_p = &addClass;
addClass.nextClass = temp;
found = 1;
}
else//works way through the class linked list to find where it goes
{
class_t *beforesearch = (students + ref)->class_p;
class_t *search = beforesearch->nextClass;
while(search != (class_t*)0 && found == 0)
{
if(search->number < addClass.number)
{
beforesearch->nextClass = &addClass;
addClass.nextClass = search;
found = 1;
}
else
{
beforesearch = search;
search = search->nextClass;
}
}
if(found == 0)
{
beforesearch->nextClass = &addClass;
found = 1;
}
}
}
带有 typedef 的头文件:
typedef struct class_t {
char name[3];
int number;
int section;
int credits;
struct class_t *nextClass;
} class_t;
typedef struct student_t {
int id;
class_t *class_p;
} student_t;