【问题标题】:Read numbers from file into a dynamically allocated array将文件中的数字读入动态分配的数组
【发布时间】:2013-10-06 06:10:50
【问题描述】:

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

这是我尝试过的:

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

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

【问题讨论】:

  • 您显示的代码分配一个数组然后泄漏它(通过返回0 而不是grades)。您还没有显示任何尝试从文件中读取值的代码。
  • 另外,该程序是否应该使用输入重定向?应该如何读取文件?
  • malloc() 返回指向具有垃圾值的已分配内存的指针,您必须自己将值分配给已分配的内存
  • 我在阅读时什么也没有得到!!!!使问题正确。你想从函数中返回数组吗?
  • 如果不清楚,我很抱歉:我想要一个函数 readGrades 从输入(文件)中读取成绩并返回一个动态分配的数组来存储它们

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


【解决方案1】:

问题:以下代码:

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

【讨论】:

  • Op 刚才在命令行的文件中写了他的管道,所以程序应该从 stdin 读取(它确实如此)。重要的部分是你的最后一行:实际返回指向已分配数组的指针。
  • 不能用./a.out
  • 我改了 return NULL;返回成绩,所以它应该返回它们,但仍然没有=(。
  • @SvenS:你说得对,抱歉,我忽略了`
  • 谢谢,用另一个 scanf 更有意义:P
【解决方案2】:

希望您正在寻找以下程序。这会读取您的 Grades.txt,创建内存并最终释放。我已经测试了以下程序,它运行良好。

#include "stdio.h"


int main(int argc, char *argv[])
{
  FILE *fp;
  int temp;
  int *grades = NULL;
  int count = 1;
  int index;

  fp = fopen("grades.txt","rb+");

  while( fscanf(fp,"%d",&temp) != EOF )

  {


    if( grades == NULL )

     {

       grades = malloc(sizeof(temp));
       *grades = temp;

       printf("The grade is %d\r\n",temp);
     }

    else
    {
       printf("The grade is realloc %d\r\n",temp);
       count++;
       grades = realloc(grades,sizeof(grades)*count);
       index = count -1;
       *(grades+index) = temp;
       //printf("the index is %d\r\n",index);

    }  

  }   


   /** lets print the data now **/

   temp = 0;

    while( index >= 0 )
    {

        printf("the read value is %d\r\n",*(grades+temp));
        index--;
        temp ++;

    }

    fclose(fp);

    free(grades);
    grades = NULL;


}

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 2020-01-22
    • 2015-06-14
    • 1970-01-01
    • 2017-11-04
    • 2011-06-15
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多