首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

请帮小弟我看看这个链表的异常在哪里

2013-08-01 
请帮我看看这个链表的错误在哪里下面这个链表是先赋值,然后输出,然后释放,但是黑窗口的输出中会有“应用程

请帮我看看这个链表的错误在哪里
下面这个链表是先赋值,然后输出,然后释放,但是黑窗口的输出中会有“应用程序错误”的提示,不知怎么改,请帮忙看看。

#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>
 


#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;
}

热点排行
Bad Request.