C代码有什么问题? [英] 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\n",maxim);
return 0;
}
上面的代码必须在输入矩阵中给出最大的元素.
问题
编译代码时,我没有收到任何错误或警告,但是在执行过程中,代码仅在接受输入后才停止运行.
问题陈述指出,必须使用 int findMax(int ** a,int m,int n).
2D数组不会衰减到指向指针的指针.通过使用:
maxim=findMax((int **)a,m,n);
您正在强迫编译器忽略您的错误.
代替
int findMax(int **a,int m,int n)
使用
int findMax(int a[][20],int m,int n)
然后,只需使用以下命令即可调用该函数:
maxim=findMax(a,m,n);
您说:
问题陈述说,必须使用 int findMax(int ** a,int m,int n).
在这种情况下,您不能将2D数组用于a
.您必须使用:
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\n",maxim);
// Deallocate memory.
for(i=0;i<m;i++)
{
free(a[i]);
}
return 0;
}
#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\n",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.
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\n",maxim);
// Deallocate memory.
for(i=0;i<m;i++)
{
free(a[i]);
}
return 0;
}
这篇关于C代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!