2015-03-08 5 views
1

la méthode qui prend en pointeur vers un pointeur comme argumentpasser un tableau 2D en une fonction en utilisant un pointeur vers un pointeur variable 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; 
    } 

Ceci est la fonction principale de l'endroit où le procédé est appelé 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; 
} 

Je veux juste savoir élément max dans un tableau 2D à l'aide d'une fonction qui prend en pointeur pour pointer du tableau. ce code fonctionne très bien, mais je cherche une meilleure approche ...

+0

quelle meilleure approche, lol? – Ulterior

+0

comme en évitant l'allocation de pointeur unique effectuée dans la fonction principale ... –

Répondre

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