The purpose of this code is to see whether a 2d array (matrix) of unknown size (it gets read from a file) has a diagonal which is all the same numbers. If so the function checkdiag should return 1.
the data in the file i`m using is as follows:
3
4 5 6
7 8 9
3 6 7
where the initial 3 represents the size of the matrix, (3x3)
I know for a fact it will run and gather the data from the file as it prints the matrix within the for loop with fscanf. But it will crash every time beyond that. I've tried many way of passing the variable to the function and have done research as to what is going on but I am stumped here.
I am new to coding and 2d array especially.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
int checkdiag(int size, int matrix[][size])
{
int i,sum=0,verif;
for(i=0;i<size;i++)
{
sum += matrix[i][i];
}
if(matrix[0][0]==((double)sum/(double)size))
verif=1;
else
verif=0;
return (verif);
}
int main()
{
FILE *filename;
char inputfile[25];
int howmany,confirmdiag;
int i,j; //Counter varibles
int **matrix; // points to the first cell of 2d array [0][0]
/* Type in exact file to open */
printf("Please type in the exact name of the data file you with to use and please make sure it is within the program folder.\nFor example: \"matrix1.txt\"\n");
gets(inputfile);
filename = fopen(inputfile,"r");
if (filename==NULL)
{
system("cls");
printf("\nCould not find the file you've requested, please make sure the file is on the same partition.\n\n");
getch();
exit(0);
}
fscanf(filename,"%d",&howmany); //Scanning file to find size of the matrix
matrix =(int **) calloc(howmany,sizeof(int*)); //Allocating memory for the ROWS of the matrix which are pointers of size (int*)
for (i=0; i<howmany; i++)
{
matrix[i] =(int *) calloc(howmany,sizeof(int));//Allocating memory for the COLUMNS of the matrix which are integers of size (int)
}
for(i=0;i<howmany;i++)
{
for(j=0;j<howmany;j++)
{
fscanf(filename,"%d",&matrix[i][j]);//Scanning the file to fill the matrix array.
}
}
confirmdiag=checkdiag(howmany, **matrix);
if (confirmdiag==1)
{
printf("The matrix is %dx%d and all the numbers on the main diagonal are the same.",howmany,howmany);
}
else if (confirmdiag==0)
{
printf("The matrix is %dx%d. All the numbers on the main diagonal are not the same.",howmany,howmany);
}
for (i=0; i<howmany; i++)
free (matrix[i]);
free(matrix);
return 0;
}
Looks good. Just a quick reminder: In your function call: **matrix sends only the first element of the matrix matrix(0,0) to the function since you are dereferencing the first entry of the first column. You need to send a pointer to pointer. Try:
and for the method definition:
Good luck!