我写了以下代码:
#include<stdio.h>
struct student{
char name[25];
double gpa;
struct student *next;
};
struct student *list_head;
struct student *create_new_student(char nm[], double gpa)
{
struct student *st;
printf("tcreating nodet");
printf("nName=%s t Gpa= %.2fn", nm, gpa);
st = (struct student*)malloc(sizeof (struct student ));
strcpy(st->name, nm);
st->gpa = gpa;
st->next = NULL;
return st;
}
void printstudent(struct student *st)
{
printf("nName %s,GPA %fn", st->name, st->gpa);
}
void insert_first_list(struct student *new_node)
{
printf("nInserting node: ");
printstudent(new_node);
new_node->next = list_head;
list_head = new_node;
}
struct student *delete_first_node()
{
struct student *deleted_node;
printf("nDeleting node: ");
printstudent(deleted_node);
list_head = list_head->next;
return deleted_node;
}
void printlist(struct student *st)
{
printf("nPrinting list: ");
while(st != NULL) {
printstudent(st);
st = st->next;
}
}
int main()
{
struct student *other;
list_head = create_new_student("Adil", 3.1);
other = create_new_student("Fatima", 3.8);
insert_first_list(other);
printlist(list_head);
other = delete_first_node();
printlist(list_head);
return 0;
}
当我运行它时,没有错误或警告。然而,它停在删除部分。消息说程序已停止工作。
你能帮我找到问题吗?
在函数delete_first_node
中,节点deleted_node
未初始化,传递给函数printstudent
试图访问其成员,导致未定义行为
函数应该是
struct student *delete_first_node(){
struct student *deleted_node = list_head;
printf("nDeleting node: ");
if(deleted_node != NULL)
{
printstudent(deleted_node);
list_head= list_head->next;
free(deleted_node);
}
else
printf("List is emtyn");
return list_head;
}