我正在为即将到来的数据结构考试做准备,并且正在处理我的代码问题。当我在Dev C ++中运行它时,show_list()不显示任何内容...而当我在linux中运行并显示它时show_list() )正常运行,但是使用此功能后,我的屏幕显示出rash动。
这是我的代码
#include <stdio.h>
#include <stdlib.h>
typedef struct student
{
char name[100];
int code;
float grd;
struct student *next;
}student;
student *head;
student *tail;
void show_list();
void add_list_end(const student *stud_ptr);
int main()
{
int code;
float grd;
student *ptr,stud;
head=NULL;
fflush(stdin);
printf("Name:");
gets(stud.name);
printf("Code:");
scanf("%d",&stud.code);
printf("Grade:");
scanf("%f",&stud.grd);
add_list_end(&stud);
show_list();
}
void add_list_end(const student *stud_ptr)
{
student *nn;
nn=(student *)malloc(sizeof(student));
*nn=*stud_ptr;
if(head==NULL)
{
head=tail=nn;
return;
}
else
{
tail->next=nn;
tail=nn;
}
}
void show_list()
{
student *ptr;
ptr=head;
while(ptr!=NULL)
{
printf("Name:%s\n",ptr->name);
printf("Code:%d\n",ptr->code);
printf("Grade:%.2f\n",ptr->grd);
ptr=ptr->next;
}
}
最佳答案
在您的main()
函数中,您忘记分配
stud.next = NULL;
因此
show_list()
跟随不确定的next
指针。
关于c - 单节点列表练习(无法正常工作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28552965/