链表保存问题 麻烦各高手帮忙解决
我先申了全局的:struct Stdinfo
{
char num[MAX]; /* for students number */
char names[MAX]; /* for students name */
float score;
struct Stdinfo *nextAddr;
};
/* here is the definition of the first structure pointer */
struct Stdinfo *tosp;
下面两个是我输入链表内容的函数:
void add_record(struct Stdinfo *p)
{
char names[MAX];
char num[MAX];
float score;
void push(struct Stdinfo *,char *,char *,float);
getchar();
printf("\n--------------------------------------------------------------------------------\n");
printf("\nEnter as many information as you wish.\n");
while (1)
{
printf("\nPlease enter the student's number:");
printf("\n(To stop entering,enter a single x)");
scanf("%s",num);
getchar();
if (strcmp(num,"x")==0)
break;
printf("Please enter the student's name:");
gets(names);
printf("Please enter the student's score:");
scanf("%f",&score);
getchar();
printf("\nNow you have input the imformation of this student successful.\n");
printf("--------------------------------------------------------------------------------\n");
push(tosp,num,names,score);
}
}
void push(struct Stdinfo *p,char *num,char *names,float score)
{
struct Stdinfo *newaddr;
newaddr=(struct Stdinfo *) malloc(sizeof(struct Stdinfo));
if (newaddr==(struct Stdinfo *) NULL)
{
printf("\nFailed to allocate memory for this structure.\n");
exit(1);
}
strcpy(newaddr->num,num);
strcpy(newaddr->names,names);
newaddr->score=score;
newaddr->nextAddr=p;
tosp=newaddr;
}
上面两个是我输入链表内容的函数
下面是我保存链表的函数:
void save_record(struct Stdinfo *tosp)
{
FILE *infile;
infile=fopen("c:\\record.txt","w"); /* to record the information in the "record.txt" file */
if(infile==NULL)
{
printf("\nFailed to open the file.\n");
exit(1);
}
while(tosp!=NULL)
{
fwrite(tosp,sizeof(struct Stdinfo),1,infile);
tosp=tosp->nextAddr;
}
fclose(infile);
}
现在是以保存就出现Null pointer assignment,且少存了最后输入的一组数据。