行列の次元が与えられているので、データ ファイル data.dat があると仮定します。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* file=fopen("data.dat","r");
int x,y;
fscanf(file,"%d %d",&x,&y);
//Read the matrix dimensions
int **A=(int**)malloc(sizeof(int*)*x);
for(int i=0;i<x;i++)
{
for(int j=0;j<y;j++)
{
A[i]=(int*)malloc(sizeof(int)*y);
}
}
//allocate the memory
for(int i=0;i<x;i++)
{
for(int j=0;j<y;j++)
{
fscanf(file,"%d",&A[i][j]);
}
}
//read the integers skipping whitespaces
for(int i=0;i<x;i++)
{
free(A[i]);
}
//free the memory we allocated
free(A);
fclose(file)
//close files
return 0;
}
fscanf は最初に次元である最初の 2 文字を読み取り、次に動的配列を malloc します。次に fscanf は、すべての空白をスキップして他のすべての整数をスキャンします。動的に割り当てたメモリを解放した後、ファイルを閉じます。
フラグ -std=c99 でコンパイルします。