[英]Declaring an array of pointers to structures in C, but not allocating memory for structure until needed
I'm trying to allocate space for an array of n
pointers to a struct named base
in C.我正在尝试为一个包含n
指针的数组分配空间,这些指针指向 C 中名为base
的结构。 I don't want to allocate the space for a struct unless it is needed.除非需要,否则我不想为结构分配空间。
If more than n
structs are required during a user session, then I'll realloc
another set of n pointers.如果在用户realloc
期间需要超过n
结构,那么我将重新分配另一组 n 个指针。
Would you please tell me if this is the correct method of declaring them, excluding any reallocation?请告诉我这是否是声明它们的正确方法,不包括任何重新分配?
One reason I'm asking is, that 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
.我要问的一个原因是,我不明白为什么printf("%d", sizeof(ptr[0]))
在尚未为base
实例分配任何 memory 之前返回sizeof(base)
。
Is it simply because it's a pointer to base and will occupy that much space?仅仅是因为它是一个指向 base 的指针并且会占用那么多空间吗?
I just wanted to make sure that I'm not allocating the space for n
structs of base before any are needed.我只是想确保在需要之前没有为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();
I will clear up a couple of things:我将澄清几件事:
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.我不明白为什么 printf("%d", sizeof(ptr[0])) 在尚未为 base 实例分配任何 memory 之前返回 sizeof(base)。
That is because sizeof
evaluates the number of bytes occupied by an object of the type of an expression at compile time .这是因为sizeof
在编译时计算表达式类型的 object占用的字节数。 Eg here the expression ptr[0]
has type struct base
so sizeof
returns the number of bytes needed to represent a struct base
object.例如,这里的表达式ptr[0]
具有struct base
类型,因此sizeof
返回表示struct base
object 所需的字节数。 This is unrelated to memory allocation.这与 memory 分配无关。
As for the rest of your code:至于你代码的rest:
ptr
to have type struct base **
.您希望ptr
具有类型struct base **
。calloc
because NULL
pointers are not guaranteed to actually have all bits set to zero.您也不想使用calloc
因为NULL
指针不能保证实际上所有位都设置为零。malloc
.最后,不需要转换malloc
返回的值。So in total:所以总的来说:
/* 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.