|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
为什么这个while循环只执行了一次就退出了?
源代码:
#include <stdio.h>
#include <stdlib.h>
#define Max 128
struct Stu
{
int ID;
int score;
char name[Max];
struct Stu* next;
};
void input(struct Stu* stu);
void input(struct Stu* stu)
{
printf("请输入学生的编号:");
scanf("%d",stu->ID);
getchar();
printf("请输入学生的姓名:");
scanf("%s",stu->name);
getchar();
printf("请输入学生的成绩:");
scanf("%d",stu->score);
}
void Add(struct Stu** school);
void Add(struct Stu** school)
{
struct Stu* stu,*temp;
stu = (struct Stu*)malloc(sizeof(struct Stu));
if(stu == NULL)
{
fputs("内存分配失败!\n",stderr);
exit(1);
}
input(stu);
if(*school == NULL)
{
*school = stu;
stu->next = NULL;
}
else
{
temp = *school;
*school = stu;
stu->next = temp;
}
}
void print(struct Stu* head);
void print(struct Stu* head)
{
struct Stu* stu;
int count = 1;
stu = head;
while(stu != NULL)
{
printf("%d:学生的ID为:%d,学生的姓名为:%s,学生的分数为:%d\n",count,stu->ID,stu->name,stu->score);
count++;
stu = stu->next;
}
}
void close(struct Stu** school);
void close(struct Stu** school)
{
struct Stu* temp;
while(*school != NULL)
{
temp = *school;
*school = (*school)->next;
free(temp);
}
}
int main(void)
{
struct Stu* head = NULL;
int ch;
while(1)
{
printf("是否录入数据(Y/N):");
do
{
ch = getchar();
}while(ch != 'Y' && ch != 'N');
if(ch == 'Y')
{
Add(&head);
}
else
{
break;
}
print(head);
close(&head);
}
return 0;
}
程序的问题在input函数中
学生编号和学生成绩都是int类型,但是scanf的时候,后面没有写&
应该是
scanf("%d",&stu->ID);
scanf("%d",&stu->score);
另外你在while(1)中调用了close函数,若多次输入数据,那也只能显示最后一次输入的数据,前面的都被你free释放掉了
|
-
|