3

ファイルから成績 (整数) を読み取り、それらが格納されている動的に割り当てられた配列を返す関数が必要です。

これは私が試したことです:

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

誰が私が間違ったことを教えてもらえますか?

4

2 に答える 2

3

うまくいけば、あなたは次のプログラムを探しています。これにより 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;


}
于 2013-09-30T12:28:05.237 に答える