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