C: 'the incompatible pointer types passing' warning is important?/Passing multi-dimentional array to function

Viewed 161

I would like to write a function that takes a pointer to multidimensional array. For example:

#include <stdio.h>

void print_matrix(int channel, int row, int column, int *matrix);

int main(void) {
    int test[4][5][6];
    int counter = 1;
    for (int channel = 0; channel < 4; channel++) {
        for (int row = 0; row < 5; row++) {
            for (int column = 0; column < 6; column++) {
                test[channel][row][column] = counter;
                counter += 1;
            }
        }
    }

    print_matrix(4, 5, 6, test);
}

void print_matrix(int channel, int row, int column, int *matrix) {
    for (int chn = 0; chn < channel; chn++) {
        for (int r = 0; r < row; r++) {
            for (int c = 0; c < column; c++) {
                printf("%d ", *(matrix + (chn * row * column + r * column + c)));
            }
            printf("\n");
        }
        printf("\n\n");
    }
}

But when I compile the code, the compiler gave following warning.

warning: incompatible pointer types passing 'int [4][5][6]' to parameter of type 'int *' [-Wincompatible-pointer-types]

Before I asked the question, I searched the warning and I found the different solution. like

void print_matrix(int channel, int row, int column, int matrix[channel][row][column]) ...

if I am not wrong, I know that C holds array as sequential. for example:

int holder[2][3][4]; // is equal to int holder[24] in ram
                     //holder[0][1][0] is equal to *(holder + 4)

My question is that the warning is important? and if I know what to do, can I ignore this warning?

1 Answers

This kind of warning is very important: in most cases, it indicates potential undefined behavior.

In your particular case, because you know the geometry of the object, and test decays to a pointer to its first element (a 2D matrix), which happens to have the same value as a pointer to the first matrix element, your code has the expected behavior.

Yet it would be better style to pass a pointer to the first matrix element explicitly:

int main(void) {
    int test[4][5][6];
    int counter = 1;
    for (int channel = 0; channel < 4; channel++) {
        for (int row = 0; row < 5; row++) {
            for (int column = 0; column < 6; column++) {
                test[channel][row][column] = counter;
                counter += 1;
            }
        }
    }

    print_matrix(4, 5, 6, &test[0][0][0]);
    return 0;
}
Related