从文件中读取数字到动态分配的数组中 [英] Read numbers from file into a dynamically allocated array

查看:125
本文介绍了从文件中读取数字到动态分配的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个从文件中读取成绩(整数)并返回存储它们的动态分配数组的函数。

I need a function that reads grades (integers) from from file and returns a dynamically allocated array in which they are stored.

这是我尝试的方法:

int *readGrades() {
int *grades;
int x;
scanf("%d", &x);
grades = malloc(x * sizeof(int));
return 0;
}

但是,运行代码时我什么也没得到。成绩存储在名为 1.in 的文件中:

However I don't get anything when I run the code. The grades are stored in file called 1.in:

29
6 3 8 6 7 4 8 9 2 10 4 9 5 7 4 8 6 7 2 10 4 1 8 3 6 3 6 9 4

,然后使用以下命令运行程序: ./ a.out< 1.in

and I run my program using: ./a.out < 1.in

有人可以告诉我我做错了吗?

Can anyone tell me what I did wrong?

推荐答案

问题: 以下代码:

Problem: The following code:

int *readGrades() {
    int *grades;
    int x;
    scanf("%d", &x);
    grades = malloc(x * sizeof(int));
    return 0;
}

读取1 int 从标准输入中,然后它分配一个 int s数组,然后它返回 s 0 会在这样使用时零初始化调用者的指针:

reads 1 int from the standard input, THEN it allocates an array of ints and it returns 0 which zero-initializes caller's pointer when used like this:

int* grades = readGrades();

解决方案: 在成绩中,该功能也应读取成绩。应该在读取和实际成绩阅读之前初始化数组,然后再循环阅读,这将初始化数组的元素。最后,应返回指向第一个元素的指针:

Solution: Apart from reading the count of grades, the function should read the grades as well. The array should be initialized BEFORE the reading and the actual reading of grades should be done in a loop, which would initialize array's elements. At the end, a pointer to the first element should be returned:

int *readGrades(int count) {
    int *grades = malloc(count * sizeof(int));
    for (i = 0; i < count; ++i) {
        scanf("%d", &grades[i]);
    }
    return grades;                // <-- equivalent to return &grades[0];
}
...
int count;
scanf("%d", &count);              // <-- so that caller knows the count of grades
int *grades = readGrades(count);  

这篇关于从文件中读取数字到动态分配的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆