请帮我看看这个链表的错误在哪里
下面这个链表是先赋值,然后输出,然后释放,但是黑窗口的输出中会有“应用程序错误”的提示,不知怎么改,请帮忙看看。
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
struct name
{
char firstname[SIZE];
char lastname[SIZE];
struct name *next;
};
int main(void)
{
struct name *head, *current;
//为链表赋值
head = (struct name *)malloc(sizeof(struct name));
puts("Please enter the firstname of a student:");
gets(head->firstname);
puts("Please enter the lastname of a student:");
gets(head->lastname);
current = (struct name *)malloc(sizeof(struct name));
head->next = current;
puts("Please enter the firstname of another student:");
while(gets(current->firstname)!=NULL && current->firstname[0] != '\0')
{
puts("Please enter the lastname of another student:");
gets(current->lastname);
current = (struct name *)malloc(sizeof(struct name));
current->next = current;
}
//输出链表
current = head;
while(current != NULL)
{
printf("%-5s %-5s\n", current->firstname, current->lastname);
current = current->next ;
}
//释放内存
current = head;
while(current != NULL)
{
free(current);
current = current->next ;
}
return 0;
}
#include <stdio.h>
#define SIZE 100
struct name
{
char firstname[SIZE];
char lastname[SIZE];
struct name *next;
};
int main(void)
{
struct name *head, *current;
head = (struct name *)malloc(sizeof(struct name));
puts("Please enter the firstname of a student:");
gets(head->firstname);
puts("Please enter the lastname of a student:");
gets(head->lastname);
head->next = NULL;//here
current = (struct name *)malloc(sizeof(struct name));
current->next = head->next;//here
head->next = current;
puts("Please enter the firstname of another student:");
while(gets(current->firstname)!=NULL && current->firstname[0] != '\0')
{
struct name *p = current;
puts("Please enter the lastname of another student:");
gets(current->lastname);
current = (struct name *)malloc(sizeof(struct name));
current->next = p->next;//here
p->next = current;
}
current = head;
while(current != NULL)
{
printf("%-5s %-5s\n", current->firstname, current->lastname);
current = current->next ;
}
current = head;
while(current != NULL)
{
struct name *p = current;//here
current = current->next ;
free(p);
}
return 0;
}