簡體   English   中英

將int [] []形式的變量傳遞給int類型的方法**

[英]Pass variable in form int[][] into method with type int**

我有一個整數的二維數組和一個從該二維數組中檢索特定列的函數。 該函數具有一個int **作為參數。 如何創建一個指向我的int [] []的int **。

int* getColumn(int **matrix, int rows, int column, int columnNum)
{
    ...
}

int main()
{
    int mat[2][2];
    mat[0][0] = 1;
    mat[0][1] = 2;
    mat[1][0] = 3;
    mat[1][1] = 4;

    getColumn( ? , 2, 2, 1);
}

沒有簡單的方法,因為它們是完全不同的類型-一種是2D數組,另一種是指向(可能是1D數組)整數的指針(可能是1D數組)。

這是int[2][2]在地址5678處的內存布局:(並假設int是一個字節,在大多數實際系統中不是這樣,但是我們假裝)

Address  5678 5679 5680 5681
        +----+----+----+----+
        | 1  | 2  | 3  | 4  |
        +----+----+----+----+
        ^ address of mat

這是一個可能的int**表示相同數組的內存布局:

Address  2345 2346 ... 3456 3457 ... 5682
        +----+----+...+----+----+...+----+----+
        | 1  | 2  |...| 3  | 4  |...|2345|3456|
        +----+----+...+----+----+...+----+----+
                                    ^ address of mat2

如您所見,它們並不相同。 主要區別在於,使用int**表示時,每一行都可以位於完全不同的地址,而“矩陣”實際上是一個數組,其中包含指向每一行的指針

但是,您可以自己創建指向每一行的指針數組:

int *rows[2] = {
    mat[0],
    mat[1]
};
getColumn(rows, 2, 2, 1);

但是,如果矩陣的大小不總是相同的話,這將變得很復雜。

(為此,內存布局為:

Address  5678 5679 5680 5681 ... 5700 5701
        +----+----+----+----+...+----+----+
        | 1  | 2  | 3  | 4  |...|5678|5680|
        +----+----+----+----+...+----+----+
        ^ address of mat        ^ address of rows

暫無
暫無

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

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