问题是-编写程序以使用函数在矩阵中找到最大元素。
功能规格:
int findMax(int ** a,int m,int n)第一个参数对应于指向矩阵的指针。第二个参数对应于矩阵中的行数。第三个参数对应于矩阵中的列数。
以下是我的代码,尽管没有编译错误,但我不知道我要去哪里。请帮助并提前致谢!
#include<stdio.h>
#include<malloc.h>
int findMax(int **a, int m, int n) {
int c,d, maximum=a[0][0];
for( c = 0 ; c < m ; c++ )
{
for( d = 0 ; d < n ; d++ )
{
if ( a[c][d] > maximum )
maximum = a[c][d];
}
} return maximum;
}
int main()
{
int m, n, c, d, maximum;
int **a = (int **)malloc(10 * sizeof(int *));
scanf("%d",&m);
printf("Enter the number of columns in the matrix\n");
scanf("%d",&n);
printf("Enter the elements in the matrix\n");
for( c = 0 ; c < m ; c++ )
{
for( d = 0 ; d < n ; d++ )
{
scanf("%d",&a[c][d]);
}
}
printf("The matrix is\n");
for( c = 0 ; c < m ; c++ )
{
for( d = 0 ; d < n ; d++ )
{
printf("%d ",a[c][d]);
}
printf("\n");
}
maximum = findMax(a,m,n);
printf("The maximum element in matrix is %d\n", maximum);
return 0;
}
您a
为的行分配了内存,但没有为a
。
for( c = 0 ; c < m ; c++ )
{
// Add this
a[c] = malloc(n*sizeof(int));
for( d = 0 ; d < n ; d++ )
{
scanf("%d",&a[c][d]);
}
}
另外,请确保添加代码以释放内存。
for( c = 0 ; c < m ; c++ )
{
free(a[c]);
}
free(a);
进一步改进:
不要使用硬编码的数字10
来为其分配内存a
,请使用m
。采用:
int m, n, c, d, maximum;
int **a = NULL
scanf("%d",&m);
printf("Enter the number of columns in the matrix\n");
scanf("%d",&n);
printf("Enter the elements in the matrix\n");
a = malloc(m * sizeof(*a));
请勿对所返回的值使用显式强制转换malloc
。请参见具体地说,强制转换malloc的结果有什么危险?。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句