C 学生结构的链表实现
我正试图用下面的结构创建一个学生的链接列表C 学生结构的链表实现,c,struct,linked-list,C,Struct,Linked List,我正试图用下面的结构创建一个学生的链接列表 struct student { int student_ID; char *student_name; struct course *courses_enrolled; Student *child; }; //Insert student to the list with a given student pointer and the starting point Student *insert_student(
struct student
{
int student_ID;
char *student_name;
struct course *courses_enrolled;
Student *child;
};
//Insert student to the list with a given student pointer and the starting point
Student *insert_student(Student *child, Student *root)
{
Student *temp = (Student*)malloc(sizeof(Student));
//if there isn't a starting point, declare this as the start point
if( root->student_name == NULL )
{
root->student_ID = child->student_ID;
root->student_name = strdup(child->student_name;);
root->child = NULL;
}
//if this student's name is before current node, replace node.
else if( strcmp( child->student_name, root->student_name ) < 0 )
{
temp = root;
root = child;
child->child = temp;
}
//if this student's name is after current node, keep doing insert recursion
else if( strcmp( child->student_name, root->student_name ) > 0 )
{
insert_student( child, root->child );
}
return root;
}
我怀疑这与我访问根的子节点(root->child)有关,但我不确定是什么
p/s:我知道我没有取消分配,这只是暂时的,因为我需要使用不同的库
更新:删除多余的代码。当您递归调用insert\u student时,您应该确保作为
根传递的值不为空。如果为null,则可能需要另一个case(比如在末尾插入)
我注意到的一点是,您从未使用temp
的分配值。在使用temp
之前,它总是未使用或丢弃。我想这不是你想要的
此外,通常在结构中使用单词next
,而不是child
,在参数中使用类似newStudent
或只是student
,而不是child
if( root->student_name == NULL )
{
printf("Always here?\n");
root->student_ID = child->student_ID;
root->student_name = strdup(child->student_name);
temp->student_ID = 0;
temp->student_name = NULL;
root->child = temp;
}
我发现我实际上需要先声明子节点的变量为NULL,然后才能访问它们。要找到确切的问题有点困难,因为我们没有给出如何调用此函数。似乎有一些事情你需要检查
我假设传递给函数的子项
和根
确实已分配,根中的所有字段都设置为NULL
,并且该学生的姓名按顺序排列,这样就不会发生第二个分支。然后,第一次插入将起作用
但是,当您执行第二次插入时。您正在传入您在第一个if
子句中设置为NULL
的root->child
。这将导致后续的strcmp失败,因为您无法从NULL
中取消引用(例如NULL->student\u name
抛出错误)。是的,您说得对,在这一部分没有失败,我已经重新检查了,我相信它实际上在比较中失败了(编辑我的帖子以反映这一点)。我还删除了临时分配,这应该是我删除的其他东西。
if( root->student_name == NULL )
{
printf("Always here?\n");
root->student_ID = child->student_ID;
root->student_name = strdup(child->student_name);
temp->student_ID = 0;
temp->student_name = NULL;
root->child = temp;
}