c - 将文件中的数字读入动态分配的数组

标签 c arrays file-io dynamic-memory-allocation formatted-input

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

这是我尝试过的:

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

但是,当我运行代码时,我什么也没得到。成绩存储在名为 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

谁能告诉我我做错了什么?

最佳答案

问题:以下代码:

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

从标准输入中读取 1 个 int,然后分配一个 ints 数组,然后 returns 0 当像这样使用时将调用者的指针初始化为零:

int* grades = readGrades();

解决方案: 该函数除了读取成绩外,还要读取成绩。数组应该在读取之前初始化,并且成绩的实际读取应该在一个循环中完成,这将初始化数组的元素。最后,应该返回指向第一个元素的指针:

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);  

关于c - 将文件中的数字读入动态分配的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19093224/

相关文章:

javascript - 使用递归的一维数组迭代

c - 有没有比我用 C 语言读取格式化文件更有效的方法?

r - 如何防止覆盖文件?

在预购中将 BST 转换为 DLL(基本)

c - 检查 C 中文件是否存在的最佳方法是什么?

c - 哲学家餐饮计划C

java - 检查整数的数字是否在增加(java)

python - 在 numpy 中重新定义 *= 运算符

python - 在 Python 中获取目录基名的优雅方法?

c - Windows重叠IO实际上是阻塞的