簡體   English   中英

指向多維數組的指針數組

[英]Array of pointers to multidimensional arrays

我有一些二維數組,如:

int shape1[3][5] =  {1,0,0,
             1,0,0,
             1,0,0,
             1,0,0,
             1,0,0};
int shape2[3][5] =  {0,0,0,
             0,0,0,
             0,1,1,
             1,1,0,
             0,1,0};

等等。

我如何制作一系列指針?

我嘗試了以下,但它們不起作用( 警告:從不兼容的指針類型初始化 ):

int *shapes[]=  {&shape1,&shape2};

int *shapes[]=  {shape1,shape2};

int **shapes[]= {&shape1,shape2};

有幫助嗎?

我相信我剛剛驗證了我寫的是正確的。 以下按預期工作:

#include <stdio.h>

int main(int argc, char **argv) {

int shape1[5][3] =  {1,0,0,
                 1,0,0,
                 1,0,0,
                 1,0,0,
                 1,0,0};

int shape2[5][3] =  {0,0,0,
                 0,0,0,
                 0,1,1,
                 1,1,0,
                 0,1,0};

typedef int (*shapes_p)[3];
shapes_p shapes[2] = { shape1, shape2 };

shapes[0][1][0] = 5;
shapes[1][1][0] = 5;

printf("shape1[1][0] == %d\n", shape1[1][0]);
printf("shape2[1][0] == %d\n", shape2[1][0]);

}

要記住的是, shape1shape2的類型實際上是:

int *shape1[5];

你在記憶中擁有的是3個相鄰的陣列,每個陣列有5個整數。 但實際類型是指向5個int的數組。 當你寫:

shape1[1][2] = 1;

你告訴編譯器索引到第二個int [5]數組,然后訪問該數組的第3個元素。 編譯器實際上做的是指向基礎類型的指針算法,在本例中為int [5]。 您可以使用以下代碼執行相同的操作:

int *p = shapes1[0];
p+7 = 1;  // same as shape1[1][2] = 1;

所以如果你想要一個指向int * [5]的指針數組,那么你會這樣做:

typedef int (*shapes_p)[5];
shapes_p shapes[2];

更新固定類型。 感謝j_radom_hacker引起我的注意!

[編輯:實際上這里的類型不正確 - 請參閱Robert S. Barnes對正確使用類型的回答 。]

首先shape1shape2的類型:

typedef int (*shape_array_t)[5];

現在用這個:

shape_array_t sat[] = { shape1, shape2 };

首先,第一個數組綁定引用最外層的數組維度,因此您應該將shape1聲明為:

int shape1[5][3] =  {1,0,0,
                     1,0,0,
                     1,0,0,
                     1,0,0,
                     1,0,0};

並且類似於shape2

[編輯:我已經改變了下面的shapes類型以對應羅伯特巴恩斯的答案 - 我們不希望最外面的下標包含在這種類型中!]

你需要的有點奇怪的類型名稱是:

int (*shapes[])[3] = { shape1, shape2 };

這允許使用shape2 2的第4行第1列的元素

shapes[1][3][0]

子表達式及其C類型的細分:

shapes            // has type "int (*x[2])[3]" (decays to "(**x)[3]")
shapes[1]         // has type "int (*x)[3]"
shapes[1][3]      // has type "int x[3]" (decays to "int *x")
shapes[1][3][0]   // has type "int x"

(請注意,上面的類型中包含了一個虛擬x以使它們更清晰 - 實際上這個標識符不是該類型的一部分。)

解碼C / C ++類型的經驗法則是“從變量名開始,在可以時讀右,在到達右括號時離開。” 所以shapes的解碼型名稱是:

指向3個整數數組的指針數組。

一般來說,對於這些復雜類型使用typedef要好得多,正如dirkgently所暗示的那樣

暫無
暫無

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

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