无法读取文件来填充结构数组

时间:2019-03-19 00:49:38

标签: c arrays struct

我正在尝试使用此文件中的值填充数组:

9383      8.86
2777     69.15
7793     83.35
5386      4.92
6649     14.21
2362      0.27
8690      0.59
7763     39.26
 540     34.26
9172     57.36
5211     53.68
2567     64.29
5782     15.30
2862     51.23
4067     31.35
3929     98.02
4022     30.58
3069     81.67
1393     84.56
5011     80.42
6229     73.73
4421     49.19
3784     85.37
5198     43.24
8315     43.70
6413     35.26
6091     89.80
9956     18.73
6862     91.70
6996     72.81

这是我的代码,可以成功编译,但是在运行代码时出现“段错误,核心转储”。

typedef struct student
{
double score;
int id;
char grades;
} Student;


void main(void)
{
    char filename[] = "scores.dat";
    FILE *input;
    Student class[MAXNUM];
    int numScores;
    double average;

    input = fopen("scores.dat", "r");

    if (input == NULL)
    {
            printf("EOF");
            exit(1);
    }
    getScores(input, class[MAXNUM]);
}


int getScores(FILE *input, Student class[])
{
    double s;
    int i, j, count = 0;

    while(fscanf(input, "%d %lf", &i, &s) == 2)
    {
            class[count].score = s;
            count++;
    }
    //loop to check what is in the array.
         for(j = 0; j< 20; j++){
            printf("%lf\n", class[j].score);
    }
}

我不确定从这里去哪里,我从未编译过程序,但无法运行。我尝试在main之前声明函数getScores,但是在编译时它仅添加了一个错误。任何帮助将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:2)

我认为问题出在getScore参数中。特别是在坚定。您说您期望一个数组(class []),但是您正在传递一个对象(class [MAXIMUM])。而且您超出范围。请记住,索引从0开始。这意味着在编码时,例如:int a [100]。最后一个元素位于a [99]中,而不是a [100]中。

在编译程序时设置-Wall。编译器是您的朋友。使用它。

答案 1 :(得分:1)

更改通话:

getScores(input, class[MAXNUM]);

将以上声明更改为此:

getScores(input, class);

它将成功运行。您正在做的是传递数组的元素,而不是数组本身的地址。

输出:

8.860000
69.150000
83.350000
4.920000
14.210000
0.270000
0.590000
39.260000
34.260000
57.360000
53.680000
64.290000
15.300000
51.230000
31.350000
98.020000
30.580000
81.670000
84.560000
80.420000