主题:关于建立和打印链表的小问题,困惑……
我想建立一个简单链表代码如下:
//基本结构:
struct Student
{
char* pName;
int cj[3];
struct Student* next;
};
//建立链表:
void creatStruct(struct Student* head)
{
struct Student* curr=(struct Student*)malloc(sizeof(struct Student));
int i=0;
clrscr();
printf("\nPlease input Name:");
scanf("%s",head->pName);
printf("\nPlease input this student's grade(3 courses.Use SPACE to separate):");
for(;i<3;++i)
scanf("%d",&(head->cj[i]));
head->next=NULL;
curr=head;
while(0!=strcmp(curr->pName,"stop"))
{
struct Student* nextStu=(struct Student*)malloc(sizeof(struct Student));
printf("\nPlease input Name:");
scanf("%s",nextStu->pName);
printf("\nPlease input this student's grade(3 courses.Use SPACE to separate):");
for(i=0;i<3;++i)
scanf("%d",&(nextStu->cj[i]));
curr->next=nextStu;
curr=nextStu;
free(nextStu);
}
free(curr);
}
//输出:
void print(struct Student* head)
{
struct Student* p=(struct Student*)malloc(sizeof(struct Student));
p=head;
while(0!=strcmp(p->pName,"stop"))
{
int i=0;
printf("\n*************");
printf("\nName:%s",p->pName);
for(i=0;i<3;++i)
printf("\nThe grade of this student is:%d",p->cj[i]);
p=p->next;
}
printf("\n");
free(p);
}
//主程序:
int main()
{
struct Student* head=(struct Student*)malloc(sizeof(struct Student));
creatStruct(head);
print(head);
free(head);
getch();
return 0;
}
很奇怪,单步跟踪的时候建立的过程没有问题,但是当输出时只能输出第一STUDENT的信息,剩下的就不正常了,且是个死循环,不停的输出同一组无效的数据。
(以输入stop为结束。)
实在搞不懂是哪里出了问题,还请高手指点。
//基本结构:
struct Student
{
char* pName;
int cj[3];
struct Student* next;
};
//建立链表:
void creatStruct(struct Student* head)
{
struct Student* curr=(struct Student*)malloc(sizeof(struct Student));
int i=0;
clrscr();
printf("\nPlease input Name:");
scanf("%s",head->pName);
printf("\nPlease input this student's grade(3 courses.Use SPACE to separate):");
for(;i<3;++i)
scanf("%d",&(head->cj[i]));
head->next=NULL;
curr=head;
while(0!=strcmp(curr->pName,"stop"))
{
struct Student* nextStu=(struct Student*)malloc(sizeof(struct Student));
printf("\nPlease input Name:");
scanf("%s",nextStu->pName);
printf("\nPlease input this student's grade(3 courses.Use SPACE to separate):");
for(i=0;i<3;++i)
scanf("%d",&(nextStu->cj[i]));
curr->next=nextStu;
curr=nextStu;
free(nextStu);
}
free(curr);
}
//输出:
void print(struct Student* head)
{
struct Student* p=(struct Student*)malloc(sizeof(struct Student));
p=head;
while(0!=strcmp(p->pName,"stop"))
{
int i=0;
printf("\n*************");
printf("\nName:%s",p->pName);
for(i=0;i<3;++i)
printf("\nThe grade of this student is:%d",p->cj[i]);
p=p->next;
}
printf("\n");
free(p);
}
//主程序:
int main()
{
struct Student* head=(struct Student*)malloc(sizeof(struct Student));
creatStruct(head);
print(head);
free(head);
getch();
return 0;
}
很奇怪,单步跟踪的时候建立的过程没有问题,但是当输出时只能输出第一STUDENT的信息,剩下的就不正常了,且是个死循环,不停的输出同一组无效的数据。
(以输入stop为结束。)
实在搞不懂是哪里出了问题,还请高手指点。