2015-06-20 73 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); 
    }