2009-04-28 108 views
4

我有一些二維陣列,如:陣列指針到多維數組

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

任何幫助:(警告:從兼容的指針類型初始化)?

回答

3

更新固定式。感謝j_radom_hacker將此引起我的注意!

[編輯:其實這裏的類型是不正確的 - 看到Robert S. Barnes' answer正確類型使用。]

搞清楚shape1第一類型和shape2

typedef int (*shape_array_t)[5]; 

現在使用這個:

shape_array_t sat[] = { shape1, shape2 }; 
+0

謝謝,但它仍然yelds相同錯誤! – pistacchio 2009-04-28 19:16:48

+0

嘿,我犯了一個錯字 - 對不起,有關:P – dirkgently 2009-04-28 19:17:31

3

首先,第一個數組綁定指向s到最外面的陣列尺寸,所以你應該聲明shape1爲:

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

,類似的還有shape2

[編輯:我已經改變了下面shapes類型對應Robert Barnes' answer - 我們不希望被包含在這種類型的最外面的下標!]

略帶奇怪的類型名稱你需要的是:

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

這使得元件的4排,使用加以解決shape2 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 s作爲dirkgently suggests這些複雜類型會更好。

5

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

#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];

你在內存中有什麼是每5個整數的3個相鄰陣列。但是實際的類型是指向5個整數的指針。當你寫:

shape1[1][2] = 1;

你告訴編譯器索引到INT [5]的第二陣列然後訪問該陣列的第三元件。編譯器實際上做的是指向底層類型的指針運算,在這種情況下是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];