Good morning,
I am trying to write in C a dynamic array that can accept different types.
The main structure is built as follows:
typedef struct st_array
{
void* array;
uint16_t size;
uint16_t used;
void ( *push )( struct st_array*, void* );
void* ( *at )( struct st_array*, uint16_t );
} st_array;
void pushInArray( st_array* this, void* item )
{
// Check for last occupied bin
// if equal size, realloc() and increase this->size
this->array[this->used++] = item;
}
void* getAt( st_array* this, utf16_t idx )
{
if( idx <= this->used )
return this->array[idx];
return NULL;
}
st_array NewArray( uint16_t size )
{
st_array this;
this.array = malloc( size * sizeof( void* ) );
this.push = &pushInArray;
this.at = &getAt;
...
return this;
}
In order to use this, I need to cast for my variable type at each call of push()
and at()
:
int item = 13;
st_array a = NewArray( 32 );
a.push( &a, (void*)&item );
int item_ret = *(int*)a.at( &a, 0 );
I'd prefer to avoid the casting (although it can be useful, just to keep the programmer aware of what is she doing). It is possible to define a function-style macro that accept the type as parameter, but I still have to figure out how to "bind" it to the structure function pointer.
I imagine the simplest solution might just be defining a function-style macro as (now written without checks to keep it short):
#define push( a, b ) a->array[a->used++] = ( void* )b
#define get( a, i, t ) *(t*)a->array[i]
and using them as:
push( &a, &item );
int item_ret = get( &a, 0, int );
but I'm not that sure on how to proceed. Can somebody please give me some advice?