c - 程序控制权传递给函数,但函数 block 中的语句未执行

标签 c function pointers multidimensional-array user-defined-functions

#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 不会执行,程序也会终止。这个程序有什么问题?

最佳答案

问题是

  1. 没有变量 m定义于 main()
  2. max = findMax((int **)a,m,n);是错的。如果你像这样通过它,你会得到一个SEGFAULT。该函数需要一个指向指针的指针。二维数组与此不同。因此,将其转换为 int**只会在稍后的代码中出现段错误。
  3. 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/

相关文章:

c++ - 返回 lambda 表达式的函数

c# - 无法在 Unity 中将结构数组从 C++ 编码到 C#

c - 为什么在尝试使用指针将两个数字相加时出现段错误?

c - 在句子中存储指向单词的指针

c - 如何从 C 中的外部函数操作 char 指针的值?

c++ - 编译器如何处理仿函数中重载的函数调用运算符?

C错误: expression must have arithmetic or pointer type

C 中的 char 指针和 strcpy

c - Scanf 检查整数的读取不起作用

r - 聚合函数在数据框中创建不需要的向量