2010-11-21 78 views
0

如何读取使用FILE * fp在C中保存的矩阵?读取文件的问题

int main() 
{ 
    int i,j; 
    FILE *fp; 
    int **mat; //matriz de cartas apartir do arquivo 
    int n; //numero de jogadores 
    mat=(char**)malloc(3*sizeof(char*)); 
    for(i=0;i<2;i++){ 
     mat[i]=(char*)malloc(3*sizeof(char)); 
     if(!mat){ 
      printf("erro de alocacao\n"); 
      exit(1); 
     } 
    } 

    fp=fopen("arquivo","r"); //this is the file to read 
    if(fp==NULL){ 
     printf("erro de abertura de ficheiro\n"); 
     exit(1); 

    } 
    for(i=0;i<3;i++){ 
     for(j=0;j<3;j++){ 
      fscanf(fp,"%d",&mat[i][j]); 
     } 
     printf("%d\n",mat[i][j]); //problem here 
    } 
    return 0; 
} 

这是矩阵我想读:

1 2 9 
3 6 7 
4 9 5 
+1

你是否想提一提你遇到的问题? – 2010-11-21 15:18:03

+0

你会得到什么输出? – rtpg 2010-11-21 15:18:53

回答

2

考虑

for(i=0;i<3;i++){ 
    for(j=0;j<3;j++){ 
     fscanf(fp,"%d",&mat[i][j]); 
} 
printf("%d\n",mat[i][j]); //problem here 

之中:

for(i=0;i<3;i++){ 
    for(j=0;j<3;j++){ 
     fscanf(fp,"%d",&mat[i][j]); 
     printf("%d ",mat[i][j]); 
    }  
    printf("\n"); 
} 

你贴什么的数组边界之外打印

+0

即使我认为这是问题。问题没有明确定义。 – prap19 2010-11-21 15:29:21

1

您正在尝试将整数读入分配给字符的空间 - 当您需要使用int时,您的malloc()操作的计算方式为sizeof(char *)sizeof(char)。这将导致问题。

您应该检查您的打印件与扫描相关的位置;目前,您尝试仅打印每行数据中的最后一个数字,但您需要考虑打印出现时j的值。

您应该也可能从scanf()检查退货状态以确保数据有效。你也许应该关闭输入文件;尽管此时程序立即退出,但“获得的资源释放”是一个很好的学科。同样的评论也可以应用到动态分配的数组中(释放你分配的内容)。