#include <stdio.h>
#include <stdlib.h>
int findMax(int **a, int m, int n)
{
int max=**a;
int i,j;
for (i=0;i<m;i++){
for (j=0;j<n;j++){
if (*(*(a+i)+j)>max){
max=*(*(a+i)+j);
}
}
}
return max;
}
int main()
{ int r,c;
printf ("Enter the number of rows in the matrix
");
scanf (" %d",&r);
printf ("Enter the number of columns in the matrix
");
scanf (" %d",&c);
printf ("Enter the elements in the matrix
");
int **a=(int **) malloc (c*sizeof(int *));
int i,j;
for (i=0;i<c;i++){
*(a+i)=(int *) malloc (r*sizeof (int));
}
for (i=0;i<r;i++){
for (j=0;j<c;j++){
scanf (" %d",(*(a+i)+j));
}
}
printf ("The matrix is
");
for (i=0;i<r;i++){
for (j=0;j<c;j++){
printf ("%d ",(*(*(a+i)+j)));
}
printf ("
");
}
printf ("The maximum element in the matrix is %d",findMax(a,r,c));
return 0;
}
I tried to write a code to find maximum element in a matrix
It gives segmentation fault if we enter 3 as rows and 2 as columns. That is, after writing 5 inputs, it ends abruptly.
Sample Input:
Enter the number of rows in the matrix
3
Enter the number of columns in the matrix
2
Enter the elements in the matrix
2
4
1
3
5
9
This input fails.
Any help would be greatly appreciated.
question from:
https://stackoverflow.com/questions/65840435/program-giving-segmentation-fault 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…