SPURTHIRAJ C G
SPURTHIRAJ C G

Reputation: 1

Find maximum element in a matrix using function findMax(int **a,int m, int n)

Hello there as mentioned in the question i need to find a maximum element in a matrix. i did got output but for some test cases the output is little weird. it gives the proper output but later it gives some warning as shown i the attached image. please tell me where i am doing wrong.!

Below is the code i used:

#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 matrix\n");
    scanf("%d",&r);
    printf("Enter the number of columns in the matrix\n");
    scanf("%d",&c);
    printf("Enter the elements in the matrix\n");
    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 is\n");
    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 ***//

Upvotes: 0

Views: 3116

Answers (1)

mziccard
mziccard

Reputation: 2178

It looks like you are deallocating a non-existing row:

for(i=0;i<=r;i++)
  free(a[i]);

The row a[1] does not exist, hence the error. Replace with:

for(i=0;i<=r-1;i++)
  free(a[i]);

Upvotes: 2

Related Questions