1

the method which takes in pointer to pointer as argument

int findMax(int **a, int m, int n)
    {
      int max=**a,i,j;
      for(i=0;i<m;i++){
        for(j=0;j<n;j++){
          if(max<=a[i][j]){
            max=a[i][j];
          }
        }
      }
      return max;
    }

This is the main function from where the findMax method is called.

int main()
    {
      // Variable Declaration
      int m,n,i,j,a[50][50],*arr[50],**arrd;

      // User Input
      printf("Enter the number of rows in the matrix\n");
      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(i=0;i<m;i++){
        for(j=0;j<n;j++){
          scanf("%d",&a[i][j]);
        }
      }
      // Single Pointer Allocation
      for(i=0;i<m;i++){
        arr[i]=&a[i][0];
      }
      arrd=&arr[0];
      // Output
      printf("The matrix is\n");
      for(i=0;i<m;i++){
        for(j=0;j<n;j++){
          printf("%d ",a[i][j]);
        }
        printf("\n");
      }
      printf("The maximum element in the matrix is %d\n",findMax(arrd,m,n));
      return 0;
}

I just want to find out max element in a 2d array using a function which takes in pointer to pointer of the array. this code works fine but i am looking for a better approach...

2
  • what better approach, lol? Commented Mar 8, 2015 at 20:13
  • as in avoiding the single pointer allocation done in the main function... Commented Mar 10, 2015 at 14:16

1 Answer 1

3
#include <stdio.h>

#define NUMCOLUMNS 50
#define NUMROWS 50

int findMax(int (*a)[NUMCOLUMNS], int m, int n)
    {
      int max=**a,i,j;
      for(i=0;i<m;i++){
        for(j=0;j<n;j++){
          if(max<=a[i][j]){
            max=a[i][j];
          }
        }
      }
      return max;
    }

int main()
{
      // Variable Declaration
      int m,n,i,j,a[NUMROWS][NUMCOLUMNS];

      // User Input
      printf("Enter the number of rows in the matrix\n");
      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(i=0;i<m;i++){
        for(j=0;j<n;j++){
          scanf("%d",&a[i][j]);
        }
      }
      // Output
      printf("The matrix is\n");
      for(i=0;i<m;i++){
        for(j=0;j<n;j++){
          printf("%d ",a[i][j]);
        }
        printf("\n");
      }
      printf("The maximum element in the matrix is %d\n",findMax(a,m,n));
      return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.