1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | typedef struct matrix { int row, col; int* data; } *MATRIX; VMatrix[7]; MATRIX newMatrix(int row, int col) { // 產生新矩陣所需的記憶體空間 MATRIX m; if ( (m = (MATRIX) malloc(sizeof(MATRIX))) == NULL ) { printf("Function newMatrix(): malloc error!\n"); return NULL; } m->row = row; m->col = col; // 產生存放資料所需的空間 if ( ( m->data = (int*)malloc(m->row*m->col*sizeof(int))) == NULL ) { printf("Function newMatrix(): m->data malloc error!\n"); return NULL; } return m; } int readMatrix() { int matrix_num; int matrix_row; int matrix_col; MATRIX m; //讀檔input.txt if( ( myfile = fopen("input.txt","r") ) == NULL ) { printf("File cannot be opened\n"); return (-1); } for ( int i = 0; i < 7; i++ ) { fscanf(myfile, "%d %d %d\n", &matrix_num, &matrix_row, &matrix_col); if ( (matrix_row < 1) || (matrix_col < 1) ) { printf("matrix error!!\n"); } m = newMatrix(matrix_row, matrix_col); for ( int i = 0; i < matrix_row; i++ ) { for ( int j = 0; j < matrix_col; j++ ) { fscanf( myfile, "%d", m->data+i*matrix_col+j ); } } VMatrix[matrix_num] = m; } //將動態分配矩陣的空間還給系統 void freeMatrix(MATRIX x) { free(x->data); free(x); } |
Direct link: https://paste.plurk.com/show/233782