我正在尝试使用以下结构创建学生的链接列表。
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;
}
第一个根插入总是可以正常工作,但是当我尝试添加第二个时,程序将在第二次调用 insert_student 后出现段错误。比较失败
if( root->student_name == NULL )
我怀疑这与我访问根的子节点(root->child)有关,但我不确定是什么。
p/s:我知道我没有取消分配,这只是暂时的事情,因为我需要使用不同的库。
更新:删除了多余的代码。