0

以下のような構造を持つファイルからデータを C の整数の多次元配列に読み込むにはどうすればよいですか?

ファイル:

3 4 30 29
23 43 4 43

動的割り当てを使用して、これを「int ** マトリックス」変数の中に入れる必要があります。

更新しました:

以下にリストされている機能間の関係を調べて調査できるサンプルコードが必要です。

  • 多次元配列とそのポインターツーポインターとの関係。
  • メモリの動的割り当てとその使用に関する説明。
  • サイズがわからない外部ソースからのデータを処理する方法、C プログラム内で行/列を配列に分割する方法。

共有コード:

int** BuildMatrixFromFile(char* infile, int rows, int cols){

    FILE *fpdata;   //  deal with the external file
    int** arreturn; //  hold the dynamic array
    int i,j;        //  walk thru the array 

    printf("file name: %s\n\n", infile);

    fpdata = fopen(infile, "r");    //  open file for reading data

    arreturn = malloc(rows * sizeof(int *));
    if (arreturn == NULL)
    {
        puts("\nFailure trying to allocate room for row pointers.\n");
        exit(0);
    }

    for (i = 0; i < rows; i++)
    {

        arreturn[i] = malloc(cols * sizeof(int));
        if (arreturn[i] == NULL)
        {
            printf("\nFailure to allocate for row[%d]\n",i);
            exit(0);
        }

        for(j=0;j<cols;++j)
            fscanf(fpdata, "%d", &arreturn[i][j]);

    }

    fclose(fpdata); // closing file buffer

    return arreturn;    
}

ありがとうございました。

4

2 に答える 2

3

誰もあなたのためにあなたのコードを書くつもりはありません。ただし、これを実現するために必要になる可能性のある標準ライブラリ関数のリストは次のとおりです。

  • fopen()
  • fscanf()
  • fclose()
  • malloc()
  • free()
于 2011-01-25T20:56:10.047 に答える
0

Numerical Recipes in Cの 20 ページから始まる説明は、メモリを割り当てる 1 つの方法を示しています。2 次元配列を行列の行へのポインターの配列として扱います。

ファイルからの行の解析はfopen()、おそらくfscanf()数字を引き出すことで達成されます。

于 2011-01-25T21:01:41.600 に答える