运行报错问题。。。求解

gy6221 2011-05-26 11:10:07
题目如下:
假设有3名学生信息,包括姓名、性别、出生年月、总分等。从键盘输入相关信息,并输出。 (使用结构指针)


#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
struct stu
{
string name;
string sex;
short bthyear;
short bthmonth;
short bthday;
int score;
stu *next;
};
stu *create()
{
stu *head;
head=NULL;
stu *now;
stu *end;

now=new stu;
cin >> now->name;
cin >> now->sex;
cin >> now->bthyear >> now->bthmonth >> now->bthday;
cin >> now->score;
end=now;
for (int i=0;i<=1;i++)
{
if (head==NULL)
head=end;
else
end->next=now;
end=now;
now=new stu;
cin >> now->name;
cin >> now->sex;
cin >> now->bthyear >> now->bthmonth >> now->bthday;
cin >> now->score;
}
end->next=NULL;
delete now;
return head;
}
void showDetail(stu *head)
{
stu *p;
p=NULL;
p=head;
for (int i=0;i<=2;i++)
{
cout << p->name << endl;
cout << p->sex << endl;
cout << p->bthyear << '-' << p->bthmonth << '-' << p->bthday << endl;
cout << p->score << endl;
p=p->next;
}
}




int main()
{
stu *head;
head=create();
showDetail(head);
system ("pause");
return 0;
}

写了这些代码,编译能通过但运行时报错。。。求解。。。
...全文
113 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
gy6221 2011-05-26
  • 打赏
  • 举报
回复
额。。。关于这问题。。。
我用结构体数组重写算了。。。
谢谢楼上各位。。。
bdmh 2011-05-26
  • 打赏
  • 举报
回复
其实是这的问题
end->next=now;和下面对now的赋值,第三次你没赋值上,导致后面显示时,访问了空指针,你应该先new,然后在end->next=now;否则先end->next=now;后面又new的now,那next就不对了
newfarmerchi 2011-05-26
  • 打赏
  • 举报
回复

void showDetail(stu *head)
{
stu *p;
p=NULL;
p=head;
for (int i=0;i<2;i++)、//<------改成就可以了

就想叫yoko 2011-05-26
  • 打赏
  • 举报
回复
你的head的next并没有设定节点
如果有多个节点就断链了
另外showDetail不应该你去指定一个i来循环
Sandax 2011-05-26
  • 打赏
  • 举报
回复
showDetail中
for (int i=0;i<=2;i++)
增加判断
for (int i=0;i<=2 && p;i++)
最好写成
while (p)
{
......
p = p->next;
}
我真的是琦琦 2011-05-26
  • 打赏
  • 举报
回复
放断点调试吧。。。。
总觉得你的create()怪怪的。。。
gy6221 2011-05-26
  • 打赏
  • 举报
回复
额。。。这个输入还没做提示。。。
自己测试时就报错了。。。

另外,输入时进入for循环之前还有一次输入,总共3次。。。应该次数没错啊
yang1216 2011-05-26
  • 打赏
  • 举报
回复
首先你这个输入也太傻了,鬼知道到底输入了什么东西。
第二,for (int i=0;i<=1;i++)
for (int i=0;i<=2;i++)
输入输出不一样多,当然会报错。

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧