链表输入后出错....
#define NULL 0
typedef struct tagstudentname
{
char name[100];
struct tagstudentname *next;
}studentname;
void main( )
{
char tmp[100];
studentname *head_studentname=NULL;
studentname *p_studentname,*tail_studentname=NULL;
p_studentname =new studentname;
cout < < "请输入学生姓名: " < <endl;
cin> > tmp;
strcpy(p_studentname-> name,tmp);
if(head_studentname==NULL)
head_studentname=p_studentname;
else
{
tail_studentname-> next=p_studentname;
tail_studentname=p_studentname;
}
p_studentname =new studentname;
cout < < "请输入学生姓名: " < <endl;
cin> > tmp;
strcpy(p_studentname-> name,tmp);
if(head_studentname==NULL)
head_studentname=p_studentname;
else
{
tail_studentname-> next=p_studentname;
tail_studentname=p_studentname;
}
}
上面只是一段测试代码,输入第一个学生的名字时正常,但是一输入第二个学生的名字就宣告程序遇到错误,需要关闭,请问是为什么?头痛中...
[解决办法]
因为当你输入第一条信息时,第一段
else
{
tail_studentname-> next=p_studentname;
tail_studentname=p_studentname;
}
这段代码不会被执行,此时tail_studentname仍然保持NULL,然后执行后一段
else
{
tail_studentname-> next=p_studentname;
tail_studentname=p_studentname;
}
代码时 tail_studentname-> next=p_studentname 自然报错 ,自己再根据需要重新改下程序的逻辑吧
[解决办法]
首先,
p_studentname =new studentname;
有内存泄漏。
在第二次操作时,head_studentname不是空的,因此会执行
tail_studentname-> next=p_studentname;
但tail_studentname是NULL
[解决办法]
for (;;)
{
tail_studentname=head_studentname;
p_studentname =new studentname;
p_studentname-> next=NULL;
cout < < "请输入学生姓名: " < <endl;
cin> > tmp;
strcpy(p_studentname-> name,tmp);
if(head_studentname==NULL)
head_studentname=p_studentname;
else
{
tail_studentname-> next=p_studentname;
tail_studentname=p_studentname;
}
}