簡體   English   中英

使用指向c中指針變量的指針將2d數組傳遞給函數

[英]Passing an 2d array into a function using a pointer to pointer variable in 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;
}

我只想使用一個函數來找出2d數組中的max元素,該函數接收指向數組的指針。 這段代碼工作正常但我正在尋找更好的方法......

#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