The code is fine. The reason for a possible segmentation fault
, is that the file could not be open (maybe file could not be found).
A problem may occur if the file doesn't contain as much data as you expect.
You could check that like this:
#include <stdio.h>
#include <stdlib.h>
int main(void) // usually we write void when main doesn't take args
{
int i;
int j;
/*matrix*/
int *mat = malloc((12* 2* sizeof ( int))); // no casting!
FILE *file;
file=fopen("test.txt", "r"); // extension file doesn't matter
if(!file) {
printf("File not found! Exiting...\n");
return -1;
}
for(i = 0; i < 12; i++)
{
for(j = 0; j < 2; j++)
{
if (!fscanf(file, "%d", &mat[i*2 + j]))
break;
printf("ok!\n");
printf("%d\n",mat[i*2 + j]); // mat[i][j] is more clean
}
}
free(mat);
fclose(file);
return 0;
}
Why not to cast what malloc
returns.
[EDIT]
A better error output could be done like this:
if(!file) { // equivalent to file == NULL
perror("File not found! Exiting...\n");
return -1;
}
Now, when the file could not be opened, you would get the output I have inside perror
and a message for the error.
I tried to open a file that it didn't exist and got
File not found! Exiting...
: No such file or directory
Probably you do not have the file in the same directory as your main file.
Credits to Olaf Dietsche and pmg for their comments.
As another answer states, you can always use a debugger
to find where is the problem.
Many people use valgrind.
As OP found out, scanf()
will fail to parse the file when the values are separated by comma and not by space.