[英]Declaring and Initializing 2D array of unknown size in C
我計划創建一個從typedef struct
派生的指針的2D數組
假設typedef struct
名為“Items”,並包含字符串和整數的混合變量。
我將聲明兩個int
變量,即typenum
和typetotal
。 這兩個整數將從零開始,並在輸入數據與某個函數匹配時相加。
在數組中, Items *type[][]
,基本上type[][]
是Items *type[typenum][typetotal]
但我不能這樣做,因為我會在聲明部分聲明typenum
和typetotal
為零。
我嘗試通過Items *type[][] = {{0},{0}}
初始化數組Items *type[][] = {{0},{0}}
但這會產生錯誤。
有什么建議? 有人告訴我在這上面使用malloc(),但我根本就不知道怎么做。
*在Windows上使用Tiny C.
使用動態內存分配。
Items **type;
type = malloc(sizeof (Items *) * typenum);
for (int i = 0; i < typenum; i++)
type[i] = malloc(sizeof Items) * typetotal);
使用陣列后,您需要手動釋放分配的內存。
for (int i = 0; i < typenum; i++)
free(types[i]);
free(types);
這是一個關於它的教程: http : //www.eskimo.com/~scs/cclass/int/sx9b.html
如果在程序運行時typenum
和typetotal
增加,請確保使用realloc
,這將重新分配更多內存並保留內容。 您需要像這樣分配數組的第一個維度:
myArray = realloc(myArray, sizeof(Items*) * typenum);
然后為第一個維度分配第二個維度:
for(...)
myArray[i] = realloc(myArray[i], sizeof(Items) * typetotal);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.