读取文件时出现分段错误(核心转储)

时间:2019-04-12 08:59:46

标签: c

我想编写一个C程序,该程序可以读取包含3x3矩阵的文件

 1 2 3 
 4 5 6
 2 8 7

但我得到:分段错误(核心已转储)

#include <stdio.h>

int main (int argc, char *argv[]){

    FILE *fp;
    int i, j;
    int mat[2][2];

    if (argc != 1) {
        if((fp = fopen(*++argv, "r")) == NULL) {
            printf("I can't open file %s\n", *argv);
            return 1;
        }
    }

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

    printf("%d",mat[2][2]);

    fclose(fp);
    return 0;
}

1 个答案:

答案 0 :(得分:4)

两个问题。

  1. 第一个问题。

    int mat[2][2];
    

    是具有索引2*2的{​​{1}}矩阵。 您需要。

    [0,1]
  2. 到目前为止,您正在将前三个数字读入对角线位置。
    您需要的是

    int mat[3][3];
    
相关问题