gpt4 book ai didi

c - 二维动态数组发送到 C 中的函数

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:40 24 4
gpt4 key购买 nike

此代码的目的是查看未知大小(从文件中读取)的二维数组(矩阵)是否具有全部相同数字的对角线。如果是这样,函数 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;
}

最佳答案

看起来不错。只是一个快速提醒:在您的函数调用中: **matrix 仅将矩阵 matrix(0,0) 的第一个元素发送到该函数,因为您正在取消引用第一列的第一个条目。您需要发送一个指向指针的指针。尝试:

confirmdiag=checkdiag(matrix, howmany, howmany);

对于方法定义:

int checkdiag(int** matrix, int sizeCol, int sizeRow)
{
...
}

祝你好运!

关于c - 二维动态数组发送到 C 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29334552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com