Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

pointers - Whats wrong with the c code?

#include<stdio.h>
int findMax(int **a,int m,int n)
{
  int max,i,j;
  max=a[0][0];
  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()
{
  int a[20][20],m,n,i,j,maxim;
  scanf("%d",&m); //Rows
  scanf("%d",&n); //Cols
  for(i=0;i<m;i++)
   for(j=0;j<n;j++)
     scanf("%d",&a[i][j]);
  maxim=findMax((int **)a,m,n);
 printf("Max is %d
",maxim);
 return 0;
}

The above code must give the maximum element in the input matrix.

PROBLEM
When the code is compiled, i'm not getting any error or warning, But DURING EXECUTION the code just stops running after taking the input.!

The problem statement says that int findMax(int **a,int m,int n) has to be used.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A 2D array does not decay to a pointer to a pointer. By using:

  maxim=findMax((int **)a,m,n);

you are forcing the compiler to ignore your error.

Instead of

int findMax(int **a,int m,int n)

use

int findMax(int a[][20],int m,int n)

and then, call the function simply using:

  maxim=findMax(a,m,n);

You said:

The problem statement says that int findMax(int **a,int m,int n) has to be used.

In that case, you have cannot use a 2D array for a. You'll have to use:

int main()
{
   // Define a to be an array of pointers.
   int* a[20];
   int m,n,i,j,maxim;

   scanf("%d",&m); //Rows

   // Make sure m not greater than 20. Otherwise, you'll end up
   // accessing memory out of bounds.
   if ( m > 20 )
   {
      // Deal with error.
   }

   scanf("%d",&n); //Cols

   for(i=0;i<m;i++)
   {
      a[i] = malloc(sizeof(int)*n);
      for(j=0;j<n;j++)
      {
         scanf("%d",&a[i][j]);
      }
   }

   maxim=findMax(a,m,n);
   printf("Max is %d
",maxim);

   // Deallocate memory.
   for(i=0;i<m;i++)
   {
      free(a[i]);
   }

   return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...