I am trying to read an array through input file in C. I am getting segmentation fault(core dumped) error after displaying array. Can anyone please solve this issue. Here is my c program
#include <stdio.h>
#include<stdlib.h>
int main()
{
int c, i, j, row, col, nl, cr,nt;
col = nl = cr = nt=0;
int k;
row=1;
FILE *fp = fopen("IO.txt", "r");
// Figure out how many rows and columns the text file has
while ((c = getc(fp)) != EOF)
{
if (c == '\n')
nl++;
if (c == '\r')
cr++;
if(c=='\t')
nt++;
col++;
if (c == '\n')
row++;
putchar(c);
}
//row=row+1;
col = (col - (nl + cr+nt));
col = (int) (col/row);
char **array = malloc(sizeof(char *) * row);
for(int k=0;k<row;k++)
{
array[c] = malloc(sizeof(char) * col);
}
if(fp)
{
for( ;; )
{
c = getc(fp);
if ( c == EOF )
{
break;
}
if ( c != '\n' && c != '\r' )
{
array[i][j] = c;
if ( ++j >= col )
{
j = 0;
if ( ++i >= row )
{
break;
}
}
}
}
fclose(fp);
}
for ( i = 0; i < row; i++ )
{
for ( j = 0; j < col; j++ )
{
putchar( array[i][j]);
}
putchar('\n');
}
free(array);
array=NULL;
return 0;
}
Here is my input file
IO.txt
0 0 0 0 0 0 0
0 0 1 0 2 0 0
0 1 0 4 3 6 0
0 0 4 0 0 5 0
0 2 3 0 0 7 8
0 0 0 0 8 0 9
0 0 0 0 8 9 0