以下のような構造を持つファイルからデータを 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;
}
ありがとうございました。