Reputation: 9
I want to write a C program that can read this file containing a 3x3 matrix
1 2 3
4 5 6
2 8 7
but I get: Segmentation fault (core dumped)
#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;
}
Upvotes: 0
Views: 82
Reputation: 12732
Two problems.
First problem.
int mat[2][2];
Is 2*2
matrix with indexes [0,1]
.
You need.
int mat[3][3];
As of now you are reading first 3 numbers into diagonal positions.
What you need is
for(i=0; i < 3; i++)
for(j=0; j < 3; j++)
fscanf(fp, "%d", &mat[i][j]);
Upvotes: 4