c - 查找矩阵中的最大元素

标签 c

<分区>

我有这个作业。基本上,我要做的是完成以下代码,该代码返回“r”行和“n”列的二维数组的最大元素。

#include <stdio.h>

int max_element(int **A, int r, int n) {
// complete the code
int max;
max = a[0][0];
for (int i = 0; i < r; i++) {
    for (int j = 0; j < n; j++) {
        if (A[i][j] > max)
            max = A[i][j];
    }
}
return max; }

// implement a main() function to test the algorithm
int main() {
int A[2][3] = { {1, 0, 4}, {10, 3, 1} };

printf("%d\n", max_element(&A, 2, 3));
return 0; }

我有 1 个警告:

  • 从不兼容的指针类型 [-Wincompatible-pointer-types] 传递 'max_element' 的参数 1

控制台停止工作:出现问题导致程序停止正常工作...

最佳答案

您的 max_element 函数定义如下:

int max_element(int **A, int r, int n);

它接受一个指向 int (int**) 的指针,而您正在向它提供:

int A[2][3];
max_element(&A, 2, 3);

您是否希望表达式 &A 产生类型为 int** 的结果?它不会。它实际上会产生 int(*)[2][3] 类型的结果。这不会绑定(bind)到 int**。这是编译器警告开始的地方。那些是不兼容的指针!

虽然你有一个更广泛的问题。二维数组不是 int**。它的类型为 int[][COLS]。您必须指定第二个数字。

将您的功能更改为:

const int COLS = 3;

int max_element(int A[][COLS], int r, int n);

然后调用为:

max_element(A, 2, 3);

关于c - 查找矩阵中的最大元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40333429/

相关文章:

c - gets() 怎么会超过 malloc() 分配的内存呢?

c - 'write' 函数的正确缓冲区大小是多少?

c - 多线程的 printf()

c - 为什么括号中的字符串会编译,编译成什么?

C中十六进制数转十进制数

c - 字符串正在打印奇怪的字符 - lex 中的 c 代码

c - 如何忽略 sscanf 中的已知单词?

c - 没有 BIO 的 ASN1_TIME_print 功能?

html - 从 HTML 表单中使用 c 程序获取数据

c - 用管道模拟 linux 命令不起作用