簡體   English   中英

C:'傳遞不兼容的指針類型'警告很重要嗎?

[英]C: 'the incompatible pointer types passing' warning is important?

我想編寫一個函數,該函數采用指向多維數組的指針。 例如:

#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)

我的問題是警告很重要嗎? 如果我知道該怎么做,我可以忽略這個警告嗎?

這種警告非常重要:在大多數情況下,它表示潛在的未定義行為。

在您的特定情況下,因為您知道對象的幾何形狀,並且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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM