在 C 中声明指向结构的指针数组,但在需要之前不为结构分配内存

Declaring an array of pointers to structures in C, but not allocating memory for structure until needed

我正在尝试为 n 指针数组分配 space,指向 C 中名为 base 的结构。我不想分配 space 用于结构,除非需要它。

如果在用户会话期间需要超过 n 个结构,那么我将 realloc 另一组 n 个指针。

你能告诉我这是不是声明它们的正确方法,不包括任何重新分配?

我问的一个原因是,我不明白为什么 printf("%d", sizeof(ptr[0])) returns sizeof(base) 在分配任何内存之前 对于 base.

的实例

难道仅仅是因为它是一个指向base的指针,会占用那么多space?

我只是想确保我没有在需要任何基础结构之前为 n 结构分配 space。

/* 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();

我会澄清几件事:

I don't understand why printf("%d", sizeof(ptr[0])) returns sizeof(base) before any memory has yet been allocated for an instance of base.

那是因为sizeof在编译时一个表达式类型的对象计算占用的字节数.例如。这里表达式 ptr[0] 的类型为 struct base 所以 sizeof returns 表示 struct base 对象所需的字节数。这与内存分配无关。

至于您的其余代码:

  • 您希望 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();