C:'传递不兼容的指针类型'警告很重要吗?

时间:2021-06-21 07:15:39

标签: arrays c pointers

我想编写一个函数,它接受一个指向多维数组的指针。例如:

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

但是当我编译代码时,编译器给出了以下警告。

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

在我问这个问题之前,我搜索了警告并找到了不同的解决方案。喜欢

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

如果我没记错的话,我知道 C 将数组保存为顺序的。例如:

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

我的问题是警告很重要吗?如果我知道该怎么做,我可以忽略此警告吗?

1 个答案:

答案 0 :(得分:2)

这种警告非常重要:在大多数情况下,它表示潜在的未定义行为。

在您的特定情况下,因为您知道对象的几何形状,并且 test 衰减为指向其第一个元素(二维矩阵)的指针,该指针恰好与指向第一个元素的指针具有相同的值矩阵元素,您的代码具有预期的行为。

然而,显式传递指向第一个矩阵元素的指针会更好:

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