c - 使用指向c中指针变量的指针将二维数组传递给函数

标签 c

以指针为参数的方法

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

这是调用 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;
}

我只想使用一个接受指向数组指针的指针的函数找出二维数组中的最大元素。 这段代码工作正常,但我正在寻找更好的方法......

最佳答案

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

关于c - 使用指向c中指针变量的指针将二维数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28930946/

相关文章:

c - 指针用++递增

c - 为什么 X 在此代码中未定义?

c - 来自 sys/stat.h 的 S_ISXXX(m) 宏出现问题

c - 语法错误 ';' 之前缺少 'type'

c - 关于 struct 内存分配机制的一些困惑?

javascript - 为 asm.js 编写优化的 JS

c - Malloc Typedef 结构问题

c - 如何在c中创建proc树

c - 停止线程池运行的好方法是什么?

c - 编译器未正确检查变量声明