#include<stdio.h>
int findMax(int **,int m,int n);
int main()
{
int n;
int a[20][20];
int i, j, max;
printf("\nEnter the number of rows in the array");
scanf("%d", &m);
printf("\nEnter the number of columns in the array");
scanf("%d", &n);
printf("\nEnter the elements of the matrix");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", a[i][j]);
}
printf("\n");
}
printf("\nThe matrix is\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%d", a[i][j]);
}
printf("\n");
}
max = findMax((int **)a, m, n);
printf("\nThe maximum element in the matrix is %d", max);
return 0;
}
int findMax(int **a, int m, int n)
{
int i, j, max;
max = a[0][0];
for(i=1; i<=m; i++)
{
for(j=1; j<=n; j++)
{
if(a[i][j] > max)
max = a[i][j];
}
}
return max;
}
程序应显示矩阵中的最大元素。应在功能 block 中找到最大值。执行该程序时,控制权被传递给功能 block ,但未分配值,整个 block 不会执行,程序也会终止。这个程序有什么问题?
最佳答案
问题是
- 没有变量
m
定义于main()
-
max = findMax((int **)a,m,n);
是错的。如果你像这样通过它,你会得到一个SEGFAULT。该函数需要一个指向指针的指针。二维数组与此不同。因此,将其转换为int**
只会在稍后的代码中出现段错误。 -
for(i=1;i<=m;i++)
和for(j=1;j<=n;j++)
将跳过数组的许多元素(它将跳过比第一个元素更多的元素,即它将跳过a[0][some other index]
和a[some index][0]
处的所有值)。
所以,你应该将你的函数更改为
int findMax(int a[][20],int m,int n)
并调用它
max = findMax(a,m,n);
并将这些 for 循环更改为普通循环,例如
for(i=0;i<m;i++)
for(j=0;j<n;j++)
这是代码的有效实现
#include<stdio.h>
int findMax(int a[][20],int m,int n);
int main()
{
int n,m;
int a[20][20];
int i,j,max;
printf("\nEnter the number of rows in the array");
scanf("%d", &m);
printf("\nEnter the number of columns in the array");
scanf("%d", &n);
printf("\nEnter the elements of the matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d", &a[i][j]);
}
}
printf("\nThe matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("%d\t", a[i][j]);
}
}
max = findMax(a,m,n);
printf("\nThe maximum element in the matrix is : %d", max);
return 0;
}
int findMax(int a[][20],int m,int n)
{
int i,j,max;
max = a[0][0];
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j] > max)
max = a[i][j];
}
}
return max;
}
关于c - 程序控制权传递给函数,但函数 block 中的语句未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29900553/