简体   繁体   中英

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. 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.

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 .

Is it simply because it's a pointer to base and will occupy that much space?

I just wanted to make sure that I'm not allocating the space for n structs of base before any are needed.

/* 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.

That is because sizeof evaluates the number of bytes occupied by an object of the type of an expression at compile time . Eg here the expression ptr[0] has type struct base so sizeof returns the number of bytes needed to represent a struct base object. This is unrelated to memory allocation.

As for the rest of your code:

  • You want ptr to have type struct base ** .
  • You also don't want to use calloc because NULL pointers are not guaranteed to actually have all bits set to zero.
  • Finally, there is no need to cast the value returned by 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM