1 #include <stdio.h> 2 #include <stdlib.h> 3 4 struct Matrix{ 5 int row; 6 int col; 7 int *mat; 8 }; 9 /*初始化一个r行c列的矩阵*/ 10 struct Matrix matrix_initialize( int r, int c ) 11 { 12 struct Matrix m; 13 m.row = r; 14 m.col = c; 15 (m.mat) = (int *) malloc( sizeof(int)*(m.row)*(m.col)); 16 return m; 17 } 18 19 /*打印矩阵到标准输出*/ 20 void matrix_show( struct Matrix m ) 21 { 22 int i,j; 23 for( i = 0; i<m.row; i++) 24 { 25 for(j = 0; j<m.col; j++) 26 { 27 printf("%d ",*(m.mat+i*(m.col)+j) ); 28 } 29 printf("\n"); 30 } 31 } 32 33 /*从文件加载矩阵,文件第一行为矩阵的行值和列值,以后为数据(int型)*/ 34 struct Matrix* load( char *file_name, struct Matrix * pm ) 35 { 36 FILE *fp; 37 if( !(fp = fopen( file_name, "r" ) ) ) 38 exit(-1); 39 //struct Matrix *pm; 40 printf("loading file %s...\n",file_name); 41 fscanf(fp,"%d%d",&(pm->row),&(pm->col)); 42 pm->mat = (int *) malloc(sizeof(int)*(pm->row)*(pm->col)); 43 int i,j; 44 for(i=0;i<pm->row;i++) 45 { 46 for(j = 0; j < pm->col; j++) 47 { 48 if( fscanf(fp,"%d",((pm->mat)+i*(pm->col)+j)) == EOF ) 49 exit(-1); 50 } 51 } 52 fclose(fp); 53 return pm; 54 } 55 56 57 int main() 58 { 59 struct Matrix m; 60 struct Matrix *pm = &m; 61 pm = load("matrix.dat",pm); 62 matrix_show(*pm); 63 return 0; 64 }
时间: 2024-10-04 18:35:22