简体   繁体   English

使用指向c中指针变量的指针将2d数组传递给函数

[英]Passing an 2d array into a function using a pointer to pointer variable in c

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. 这是调用findMax方法的主要函数。

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. 我只想使用一个函数来找出2d数组中的max元素,该函数接收指向数组的指针。 this code works fine but i am looking for a better approach... 这段代码工作正常但我正在寻找更好的方法......

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM