2015-06-20 32 views
1

以下是問題 - 編寫一個程序,使用函數來查找矩陣中的最大元素。使用雙指針數組的函數 - 在矩陣中查找最大值

功能規範:

INT findMax(INT **一個,INT米,INT N) 第一個參數對應於所述指針矩陣。 第二個參數對應於矩陣中的行數。 第三個參數對應於矩陣中的列數。

以下是我的代碼,雖然沒有編譯錯誤,但我不知道錯在哪裏。請提前幫助和感謝!

#include<stdio.h> 
#include<malloc.h> 
int findMax(int **a, int m, int n) { 
    int c,d, maximum=a[0][0]; 
    for(c = 0 ; c < m ; c++) 
    { 
     for(d = 0 ; d < n ; d++) 
     { 
     if (a[c][d] > maximum) 
      maximum = a[c][d]; 
     } 
    } return maximum; 
} 

int main() 
{ 
    int m, n, c, d, maximum; 
    int **a = (int **)malloc(10 * sizeof(int *)); 
    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(c = 0 ; c < m ; c++) 
    { 
     for(d = 0 ; d < n ; d++) 
     { 
     scanf("%d",&a[c][d]); 
     } 
    } 
printf("The matrix is\n"); 

    for(c = 0 ; c < m ; c++) 
    { 
     for(d = 0 ; d < n ; d++) 
     { 
     printf("%d ",a[c][d]); 
     } 
    printf("\n"); 
    } 

    maximum = findMax(a,m,n); 

    printf("The maximum element in matrix is %d\n", maximum); 

    return 0; 
} 

回答

3

你爲a但不爲a行分配的內存。

for(c = 0 ; c < m ; c++) 
{ 
    // Add this 
    a[c] = malloc(n*sizeof(int)); 

    for(d = 0 ; d < n ; d++) 
    { 
     scanf("%d",&a[c][d]); 
    } 
} 

此外,還要確保將代碼添加到解除分配內存。

for(c = 0 ; c < m ; c++) 
{ 
    free(a[c]); 
} 
free(a); 

進一步改進:

代替使用硬編碼號碼10a分配存儲器,使用m。用途:

int m, n, c, d, maximum; 
int **a = NULL 

scanf("%d",&m); 
printf("Enter the number of columns in the matrix\n"); 
scanf("%d",&n); 
printf("Enter the elements in the matrix\n"); 

a = malloc(m * sizeof(*a)); 

不要使用顯式的由malloc返回的值。見Specifically, what's dangerous about casting the result of malloc?

+0

這真的很有幫助!非常感謝! –

+0

再次感謝! :) –

+0

@ user3193036,很高興我能幫上忙。 –

0
#include<stdio.h> 
#include<malloc.h> 
int findMax(int **a,int m,int n); 
int max; 
int main() 
{ 
    int **b,r,c,i,j,y; 
    printf("Enter the number of rows in the matrix\n"); 
    scanf("%d",&r); 
    printf("Enter the number of columns in the matrix\n"); 
    scanf("%d",&c); 
    printf("Enter the elements in the matrix\n"); 
    b=malloc(sizeof(int*)*r); 
    for(i=0;i<r;i++) 
    { 
    b[i]=malloc(sizeof(int*)*c); 
    for(j=0;j<c;j++) 
    { 
     scanf("%d",&b[i][j]); 
     } 
    } 
    printf("The matrix is\n"); 
     for(i=0;i<r;i++) 
     { 
     for(j=0;j<c;j++) 
     { 
      printf("%d ",b[i][j]); 
     } 
     printf("\n"); 
     } 
    y=findMax(b,r,c); 
     printf("The maximum element in the matrix is %d\n",y); 
    return(0); 
} 
int findMax(int **a,int m,int n) 
{ 
    int i,j; 
    for(i=0;i<m;i++) 
    { 
    for(j=0;j<n;j++) 
    { 
     if(a[i][j]>max) 
     max=a[i][j]; 
    } 
    } 
    return(max); 
    }