以下代码获取从在一维阵列中的文件并将其存储输入。我想输入的像的矩阵式:转换数组大小
1,2,4
3,4,5
5,6,7
(或)
2,3,4,5
4,5,6,7
7,6,5,4
3,4,5,6
其中矩阵的大小而变化,并且它们由逗号分隔的,要被存储在2D阵列。我应该对下面的代码做些什么改变?
#include <stdio.h>
#include <stdlib.h>
int main(){
char file[51];
int data, row, col, c, count, inc;
int *array, capacity=50;
char ch;
array = (int*)malloc(sizeof(int) * capacity);
printf("\nEnter the name of the file with its extention\n");
scanf("%s", file);
FILE *fp = fopen(file, "r");
row = col = c = count = 0;
while (EOF != (inc = fscanf(fp,"%d%c", &data, &ch)) && inc == 2){
++c; //COLUMN count
if (capacity == count)
array = (int*)realloc(array, sizeof(int) * (capacity *= 2));
array[count++] = data;
if(ch == '\n'){
++row;
if (col == 0){
col = c;
} else if (col != c){
fprintf(stderr, "format error of different Column of Row at %d\n", row);
goto exit;
}
c = 0;
} else if (ch != ',') {
fprintf(stderr, "format error of different separator(%c) of Row at %d \n", ch, row);
goto exit;
}
}
{ //check print
int i, j;
//int (*matrix)[col] = array;
for(i = 0; i < row; ++i){
for(j = 0; j < col; ++j)
printf("%d ", array[i * col + j]);//matrix[i][j]
printf("\n");
}
}
exit:
fclose(fp);
free(array);
return 0;
}
他们说[你不应该在C]中抛出'malloc()'的结果(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 – MikeCAT
进行的更改之一:向内存分配和文件打开添加错误检查。 – MikeCAT
谢谢你。更改记录。 – Raj