请帮小弟我看看这个链表的异常在哪里
请帮我看看这个链表的错误在哪里
下面这个链表是先赋值,然后输出,然后释放,但是黑窗口的输出中会有“应用程序错误”的提示,不知怎么改,请帮忙看看。
------解决方案--------------------
new时,next要指向NULL
------解决方案--------------------
1、第一个while有问题,你一直在重复利用一个变量,这里起码还需要另一个变量
2、free那里由于先free了current,下面又引用current,肯定会产生段错误。
------解决方案--------------------
已帮你改正
下面这个链表是先赋值,然后输出,然后释放,但是黑窗口的输出中会有“应用程序错误”的提示,不知怎么改,请帮忙看看。
#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;
}
------解决方案--------------------
new时,next要指向NULL
------解决方案--------------------
1、第一个while有问题,你一直在重复利用一个变量,这里起码还需要另一个变量
2、free那里由于先free了current,下面又引用current,肯定会产生段错误。
------解决方案--------------------
已帮你改正
#include <stdio.h>