Orion Orion - 1 year ago 119
C Question

Find max element in a matrix

I've got this homework. Basically, what I have to do is complete the following code that returns the maximum element of a bidimensional array of 'r' rows and 'n' columns.

#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; }

I have 1 warning:

  • passing argument 1 of 'max_element' from incompatible pointer type [-Wincompatible-pointer-types]

The console stopped working: a problem caused the program to stop working correctly...

Answer Source

Your max_element function is defined as such:

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

It takes a pointer to a pointer to int and you are feeding it this:

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

Do you except the expression &A to yield a result of type int**? It will not. It will in fact yield a result of type int(*)[2][3]. That will not bind to int**. This is where the compiler warning kicks in. Those are incompatible pointers!!

You have a wider problem though. A 2D array is not int**. It has type int[][COLS]. You must specify the second number.

Change your function to be:

const int COLS = 3;

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

and then call as:

max_element(A, 2, 3);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download