I'm writing a program which reads a .txt file and creates a array from it. The first integer in the file is the number which represents what the dimensions of the 2D array is going to be. I've succesfully have read the integers into the array but I'm having trouble with the helper function.
My txt file is:
7
1 2 3 4 5 6 8
1 1 3 4 5 6 9
1 6 1 8 5 4 3
8 3 4 1 6 7 5
4 5 6 3 1 9 7
2 5 6 8 3 1 8
3 4 5 6 7 8 1
and my code is:
Code:
#include <stdio.h>
int checkdiag (int matrix[], int col, int row);
int
main (void)
{
FILE *f1;
int col,row,row2,both,both2, *matrix, i, j,q;
/*Opened up my .txt file (named Matrix8.txt)*/
f1= fopen("Matrix8.txt", "r");
/*got the integer value in the beginning*/
fscanf (f1, "%d", &both);
printf ("The dimensions of the matrix is %dX%d\n\n", both,both);
/*if the dimensions is greater than 100, than it is invalid*/
if (both > 100)
{
printf ("The matrix size is invalid. It has to be shorter than: 100X100.\n\n");
}
/*made it into a dynamic allocated array*/
col=both;
row=both+1;
row2=both;
matrix = (int *) calloc (row2*col, sizeof(int));
/*scaned the file and printed it on the screen*/
printf ("The array is: \n");
for (i=1; i<row; i++)
{
for (j=0; j<col; j++)
{
fscanf (f1, "%d", &matrix[i*col+j]);
}
}
for (i=1; i<row; i++)
{
for (j=0; j<col; j++)
{
printf ("%d ", matrix[i*col+j]);
}
printf("\n");
}
printf ("\n\n");
/*This is where i am mainly have trouble. From this point my program has an issue*/
printf ("%d\n\n", checkdiag (matrix,col,row));
free (matrix);
fclose(f1);
return (0);
}
/*main program ends*/
/*helper function to read the diagonal and display 1 if all the integers are the same or display 0 if they are not*/
int checkdiag (int matrix[], int col, int row)
{
int both,i,j,t,row2,c,c1;
FILE *f1;
f1= fopen("Matrix8.txt", "r");
fscanf (f1, "%d", &both);
row=both+1;
col=both;
row2=both;
/*I am pretty sure that this is where the problem is occuring but I do not know how to fix it.*/
for (i=1; i<row; i=j)
{
j=0;
for (j=0; j<col; j++)
{
c1=matrix[i * col+j];
}
c=matrix[i*col+j];
if (c==c1)
{
t=1;
}
else
{
t=0;
}
}
fclose(f1);
return(t);
}
The purpose of my program is to read the diagonal of the matrix in the txt file and if the diagonal is the same (has the same integers throughout the main diagonal) it will return a 1 but if it is not than it will return a 0.