【发布时间】:2015-03-29 20:37:47
【问题描述】:
此代码的目的是查看未知大小(从文件中读取)的二维数组(矩阵)是否有一个对角线,该对角线的数字都是相同的。如果是这样,函数 checkdiag 应该返回 1。
我正在使用的文件中的数据如下:
3
4 5 6
7 8 9
3 6 7
其中最初的 3 代表矩阵的大小,(3x3)
我知道它会运行并从文件中收集数据,因为它使用 fscanf 在 for 循环中打印矩阵。但每次超出此范围时,它都会崩溃。 我已经尝试了很多将变量传递给函数的方法,并对发生的事情进行了研究,但我在这里被难住了。
我是编码新手,尤其是二维数组。
#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;
}
【问题讨论】:
-
它究竟是从哪里开始崩溃的?你用调试器找出来了吗?
-
@DarkRiot43 我不明白。您是否需要检查主对角线上的所有元素是否彼此相等?
-
失败的错误是什么?它在哪里出错(行号)?您是否尝试过附加调试器并单步执行代码?您是否尝试过打印出变量的值(printf 调试)?
-
@VladfromMoscow 是的,它们应该都是同一个数字。
-
@ha9u63ar 调用该函数时似乎崩溃了。我试过用 gbd.exe 调试,没有任何结果。