C高手来帮忙

来源:百度知道 编辑:UC知道 时间:2024/05/15 02:22:34
#include "stdio.h"
#include"malloc.h"
#include"string.h"
#define NULL 0
struct STU
{
char name[20];
int age;
struct STU *next;
};
main()
{
int i,age;
char name[20];
struct STU *p,*q,*h;
p=q=h=NULL;
for(i=0;i<5;i++)
{

gets(name);

scanf("%d",&age);
q=(struct STU *)malloc(sizeof(struct STU));
strcpy(p->name,name);
q->age=age;
q->next=NULL;
if(p=NULL)
p=h=q;
else
{
p->next=q;
p=q;
}
}
while(p!=NULL)
{
printf("%s %d\n",p->name,p->age);
p=p->next;
}
while(h!=NULL)
{
p=h;
h=h->next;
free (p);
}
}
上面是我写的,
不知道错哪儿了.
那为高手指点下.谢了~
要求是:(1)通过键盘输入5个学生的信息;

(2)遍历链表,并输出学生的

你的错误比较典型,我改了一下,你可以参考一下,
我先说一下你的两个比较致命的错误。
f(p=NULL) //这句 应该是p==NULL;
strcpy(p->name,name);//这里的p还没有分配内存,只是一个野指针,你这样做,错了。

下面是我在你得基础上改的,

#include "stdio.h"
#include "malloc.h"
#include "string.h"
#include "iostream.h"
#define NULL 0
struct STU
{
char name[20];
int age;
struct STU *next;
};
main()
{
int i,age;
char name[20];
struct STU *p,*q,*h;
p=q=h=NULL;
for(i=0;i<5;i++)
{
cin>>name;
scanf("%d",&age);
cout<<age<<endl;
q = (struct STU *)malloc(sizeof(struct STU));
strcpy(q->name,name);
q->age = age;
q->next = NULL;
if(p==NULL)
p=h=q;
else
{
p->next=q;
p=q;
}
}
p = h;
while(p!=NULL)
{
printf("%s %d\n",p->name,p->age);