奇怪的函数调用问题

来源:百度知道 编辑:UC知道 时间:2024/06/05 21:01:26
#define N 6
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct studen
{char name[20];
int rank;
int average;
}STU;

STU *student;

main()
{ int i;
FILE *fp;
student=(STU *)malloc(6*sizeof(STU));

if((fp=fopen("9-20.dat","r"))==NULL)
printf("Open file erro!\n");
for(i=0;!feof(fp);i++)
{fscanf(fp,"%s %d %d",student[i].name,&student[i].rank,&student[i].average);
;
}
fclose(fp);
}
上面是正确的
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct studen
{char name[20];
int rank;
int average;
}STU;

STU *student;

read()
{ int i;
FILE *fp;
student=(STU *)malloc(6*sizeof(STU));

if((fp=fo

试试在student=(STU *)malloc(6*sizeof(STU));
后面加个测试看看分配内存可成功了?
if(0 == student)
{
printf("Error by alloc memory.\r\n");
return;
}

BTW:记得malloc后要在程序末尾free(student); 养成好习惯哦~:)

gcc下下面代码测试是成功的,看看文件名是不是改成19-20.dat了。

#define N 6
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct studen
{char name[20];
int rank;
int average;
}STU;

STU *student;

#if 0
main()
{ int i;
FILE *fp;
student=(STU *)malloc(6*sizeof(STU));

if((fp=fopen("9-20.dat","r"))==NULL)
printf("Open file erro!\n");
for(i=0;!feof(fp);i++)
{fscanf(fp,"%s %d %d",student[i].name,&student[i].rank,&student[i].average);
printf("%s %d %d\r\n",student[i].name,student[i].rank,student[i].average);
}
fclose(fp);
free(