2010-07-18 48 views
9

我目前正試圖瞭解如何在C中實現一個二維數組結構。我的代碼一直崩潰,我真的要讓它結束就像我所有的方法都堅定地使用C:垃圾。這是我的了:如何在C中實現結構的二維數組C

typedef struct { 
    int i; 
} test; 

test* t[20][20]; 
*t = (test*) malloc(sizeof(test) * 20 * 20); 

我的光榮錯誤:

error: incompatible types when assigning to type ‘struct test *[20]’ from type ‘struct test *’

我必須seperately分配的內存每2維?我越來越瘋了。它應該是如此簡單。有一天,我將建立一個時間機器和磁化一些C編譯器,軟盤...

回答

22

這應該是足夠了:

typedef struct { 
    int i; 
} test; 

test t[20][20]; 

這將申報的test二維數組大小爲20 x 20.不需要使用malloc。

如果您要動態分配數組您可以這樣做:

// in a function of course 
test **t = (test **)malloc(20 * sizeof(test *)); 
for (i = 0; i < 20; ++i) 
    t[i] = (test *)malloc(20 * sizeof(test)); 
+0

非常感謝! – Mortezaipo 2017-01-17 21:55:14

6
test **t; 

t = (test **)malloc(sizeof(test *) * 20); 
for (i = 0; i < 20; i++) { 
    t[i] = (test *)malloc(sizeof(test) * 20); 
} 
+0

的計數你錯過了20 – IVlad 2010-07-18 11:57:22

+3

固定。我討厭c。 – BobTurbo 2010-07-18 12:00:53

3

其他答案顯示如何解決它,但他們沒有解釋爲什麼。正如編譯器暗示的那樣,原始示例中t的類型實際上是test *[20],這就是爲什麼您投到test *還不夠。

在C中,維數N的數組T的名稱實際上是*T[dim0][dim1]...[dimN-1]類型。樂趣。

1

從我的觀察,你可能不知道你想要什麼,並混淆了結構和指針算術。請通過以下2種可能性。

1)具有每個元素的二維數組具有指向test的指針。 在這種情況下,內存的所有指針test s已經靜態地被分配爲。 但是,內存的真實test s尚未準備好。 在這種情況下,您必須逐個填寫test [i][j]

test中的每一個在內存中都是離散的,您可以動態創建或破壞它們。

typedef struct { 
    int i; 
} test; 

test* t[20][20]; 
/* or instead of statically allocated the memory of all the pointers to tests 
    you can do the following to dynamically allocate the memory 
    test ***t; 
    t = (test***)malloc(sizeof(test *) * 20 * 20); 
*/ 

for (int i=0; i < 20; i++){ 
    for (int j=0; j < 20; j++){ 
     t[i][j] = malloc(sizeof(test)); 
    } 
} 

2)每個元素的二維數組是test。 在這種情況下,內存的所有test s已經分配。 此外,內存的真實test s準備使用沒有額外的準備。

所有的test都是作爲一個大塊連續存儲在內存中,並始終存在。這意味着如果您在某個高峯時間只需要所有的test s,並且大部分時間只使用其中的一部分,則可能浪費大量內存。

typedef struct { 
    int i; 
} test; 

test t[20][20]; 
/* or instead of statically allocated the memory of all tests 
    you can do the following to dynamically allocate the memory 
    test **t; 
    t = (test**)malloc(sizeof(test) * 20 * 20); 
*/ 
0

而且,只要你的內部尺寸的大小是固定的,你可以分配一個可變數量的內部尺寸

int n = ...; 
test (*t)[20] = malloc(sizeof (*t) * n); 
t[0 .. (n-1)][0 .. 19] = ...;