[英]Pointer Array Malloc (C Programming)
我發現我不理解這一行。 它說
char (*storage)[15] = malloc(sizeof *storage * 8)
有人知道這是什么意思嗎? 為什么我看到很多*
?
我不明白這是因為為什么他/她乘以8(看起來是這樣),然后又宣布也是[15]
?
如果我錯了糾正我。
char (*storage)[15] = malloc(sizeof *storage * 8)
它為大小為15
8
字符數組分配內存。
對於所有*
您問-
char (*storage)[15] // pointer to array of 15 chars
和這個 -
sizeof *storage * 8 // this is 8 times sizeof type to which storage points
char (*storage)[15]
是char
15個元素的數組的指針。
sizeof *storage * 8
是storage
點類型的大小的8倍。
char (*storage)[15] = malloc(sizeof *storage * 8);
動態分配一個8x15的char
數組。 這大致類似於寫作
char storage[8][15];
除了那個
free
顯式釋放它為止,而自動分配對象的生命周期一直持續到程序退出該對象的封閉范圍為止。 size_t curRows = 8; char (*tmp)[15] = realloc( storage, sizeof *storage * (curRows + 2)); if ( tmp ) { storage = tmp; curRows += 2; }
您不能使用自動分配的數組來做到這一點。 動態分配8x15數組的另一種方法是這樣的:
char **storage = malloc( sizeof *storage * 8 );
if ( storage )
{
for ( size_t i = 0; i < 8; i++ )
{
storage[i] = malloc( sizeof *storage[i] * 15 );
}
}
注意,所有三個版本都可以索引為storage[i][j]
。
last方法的主要優點是,如果您希望每行的長度可以不同。 主要缺點是行在內存中不一定會相鄰,因此必須先free
每個storage[i]
然后才能free
storage
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.