c++高手帮我看看这个程序为什么不能运行,谢谢!

来源:百度知道 编辑:UC知道 时间:2024/06/23 02:24:08
typedef struct students
{
int num;
char name[20];
char sex;
int age;
char member;
struct students *next;
}stu;

stu *list( )
{
stu *ps,*head,*q;
int n,i,num,name,sex,age,member;
q=head=(stu *)malloc(sizeof(stu));
head->next =NULL;
cout<<"Enter student number:";
cin>>n;
for(i=1;i<=n;i++)
{cin>>num>>name>>sex>>age>>member;
ps=(stu *)malloc(sizeof(stu));
ps->num=num;
strcpy(ps->name ,"name");
ps->sex=sex;
ps->age=age;
ps->member=member;
ps->next =NULL;
q->next=ps;
q=ps;
}
q=head;
head=q->next ;

free(q);
return(head);

}

void main(int agrc,char *agrv[])
{stu *head,*p;
head=list();
p=head;
while(p->next!=NULL)
{cout<&l

错误很多
第一:strcpy(ps->name ,"name");你弄的是个常字符串,不管你怎么输入name,ps->name都只会是"name"。
第二:list( )中不能放掉最前面的那个头结点,试想假如我只有一个节点,while循环一开始p->next就等于NULL了。
第三:节点结构中name,sex,member都是字符或字符数组型,你输入的都是int型。
第四:致命点,你下面用了个p++,这个只是让p指向下移而已,而不是让p指向下移个节点。
修改后的程序如下:
#include <iostream>
#include <iomanip>
using namespace std;
typedef struct students
{
int num;
char name[20];
char sex;
int age;
char member;
struct students *next;
}stu;

stu *list( )
{
stu *ps,*head,*q;
int n,i,num,age;
char name[20],sex,member;
q=head=(stu *)malloc(sizeof(stu));
head->next =NULL;
cout<<"Enter student number:";
cin>>n;
for(i=1;i<=n;i++)
{cin>>num>>name>>sex>>age>>member;
ps=(stu *)malloc(sizeof(stu));
ps->num=num;
strcpy(ps->name ,name);