Reputation: 2891
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();
Upvotes: 0
Views: 144
Reputation: 3164
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. E.g. 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:
ptr
to have type struct base **
.calloc
because NULL
pointers are not guaranteed to actually have all bits set to zero.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();
Upvotes: 3