c - 单节点列表练习(无法正常工作)

标签 c singly-linked-list

我正在为即将到来的数据结构考试做准备,并且正在处理我的代码问题。当我在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/

相关文章:

java - 编译器不会推进单链表的递归反转

android - ndk 中的 LocalBroadcastManager

c - 我的二进制到十进制方法的无限循环错误?

c - Node *head 与 Node **head 之间有什么区别?

c - 插入节点并按字母顺序排列

java - 链表的动态实现

c - 删除链表中给定位置的节点

c - SIGSEGV 段错误,不同的消息

c - 如何在C中打印\\? (fprintf)

c - 将结构传递给 C 中的函数