I\'m trying to find a way to make a struct to hold a dynamic array that can work with any data type (Including user defined data types), so far this is what I came up with.<
The second example won't work because the two variable are defined as distinct types even though their members are the same. Why is this so, is covered in my existing answer.
However the syntax can be kept the same using a slightly different approach:
#include
#define vector(type) struct vector_##type
struct vector_int
{
int* array;
size_t count;
} ;
int main(void)
{
vector(int) one = { 0 };
vector(int) two = { 0 };
one = two;
( void )one ;
return 0;
}
The usage surprisingly similar to C++'s vector and a full example can be seen here:
#include
#define vector_var(type) struct vector_##type
struct vector_int
{
int* array;
size_t count;
};
void vector_int_Push( struct vector_int* object , int value )
{
//implement it here
}
int vector_int_Pop( struct vector_int* object )
{
//implement it here
return 0;
}
struct vector_int_table
{
void( *Push )( struct vector_int* , int );
int( *Pop )( struct vector_int* );
} vector_int_table = {
.Push = vector_int_Push ,
.Pop = vector_int_Pop
};
#define vector(type) vector_##type##_table
int main(void)
{
vector_var(int) one = { 0 };
vector_var(int) two = { 0 };
one = two;
vector(int).Push( &one , 1 );
int value = vector(int).Pop( &one );
( void )value;
return 0;
}