[英]Declaring an array of pointers to structures in C, but not allocating memory for structure until needed
我正在嘗試為一個包含n
指針的數組分配空間,這些指針指向 C 中名為base
的結構。 除非需要,否則我不想為結構分配空間。
如果在用戶realloc
期間需要超過n
結構,那么我將重新分配另一組 n 個指針。
請告訴我這是否是聲明它們的正確方法,不包括任何重新分配?
我要問的一個原因是,我不明白為什么printf("%d", sizeof(ptr[0]))
在尚未為base
實例分配任何 memory 之前返回sizeof(base)
。
僅僅是因為它是一個指向 base 的指針並且會占用那么多空間嗎?
我只是想確保在需要之前沒有為n
個 base 結構分配空間。
/* Global declaration */
struct base { ... };
struct base *ptr;
/* in main() */
ptr = calloc( n, sizeof ( char ) );
/* Function to return pointer to newly allocated struct base */
struct base *base_alloc( void )
{
return ( struct base * ) malloc( sizeof ( struct base ) );
}
/* Within a function to create new base and populate it.*/
ptr[i] = base_alloc();
我將澄清幾件事:
我不明白為什么 printf("%d", sizeof(ptr[0])) 在尚未為 base 實例分配任何 memory 之前返回 sizeof(base)。
這是因為sizeof
在編譯時計算表達式類型的 object占用的字節數。 例如,這里的表達式ptr[0]
具有struct base
類型,因此sizeof
返回表示struct base
object 所需的字節數。 這與 memory 分配無關。
至於你代碼的rest:
ptr
具有類型struct base **
。calloc
因為NULL
指針不能保證實際上所有位都設置為零。malloc
返回的值。所以總的來說:
/* Global declaration */
struct base { ... };
struct base **ptr;
/* in main() */
ptr = malloc( n * sizeof *ptr );
for (size_t i = 0; i < n; ++i)
{
ptr[i] = NULL;
}
/* Function to return pointer to newly allocated struct base */
struct base *base_alloc( void )
{
return malloc( sizeof ( struct base ) );
}
/* Within a function to create new base and populate it.*/
ptr[i] = base_alloc();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.