從我的觀察,你可能不知道你想要什麼,並混淆了結構和指針算術。請通過以下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);
*/
非常感謝! – Mortezaipo 2017-01-17 21:55:14