你好,正如问题中提到的,我需要在矩阵中找到一个最大元素。我确实得到了输出,但对于一些测试用例,输出有点奇怪。它给出了正确的输出,但后来它给出了一些警告,如所附图像所示。请告诉我哪里做错了。!
下面是我使用的代码:
#include<stdio.h>
#include<stdlib.h>
int findMax(int **a,int m, int n)
{
int i,j,max=0;
for(i=0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
{
if(max<a[i][j])
max=a[i][j];
}
}
return max;
}
int main()
{
int* a[20];
int i,j,r,c,s=0;
printf("Enter the number of rows in the matrixn");
scanf("%d",&r);
printf("Enter the number of columns in the matrixn");
scanf("%d",&c);
printf("Enter the elements in the matrixn");
for(i=0;i<=r-1;i++)
{
a[i]=malloc(sizeof(int)*c);
for(j=0;j<=c-1;j++)
scanf("%d",&a[i][j]);
}
printf("The matrix isn");
for(i=0;i<=r-1;i++)
{
for(j=0;j<=c-1;j++)
printf("%d ",a[i][j]);
printf("n");
}
s=findMax(a,r,c);
printf("The maximum element in the matrix is %d",s);
for(i=0;i<=r;i++)
free(a[i]);
return 0;
}
//Enter the number of rows in the matrix
//> 1
//> Enter the number of columns in the matrix
//> 2
//> Enter the elements in the matrix
//> 3
//> 56
//> The matrix is
//3 56
//The maximum element in the matrix is 56*** glibc detected *** a.out: //munmap_chunk(): invalid pointer: 0x08048307 ***//
看起来您正在释放一个不存在的行:
for(i=0;i<=r;i++)
free(a[i]);
行a[1]
不存在,因此出现错误。替换为:
for(i=0;i<=r-1;i++)
free(a[i]);