I am trying to copy a void pointer to different indexes of another pointer array, things work fine for characters but there appears problem for integer and doubles
Here is my strcture:
typedef struct vector_struct {
size_t e_sz;
char e_type;
#define V_INT 1
#define V_DOUBLE 2
#define V_CHAR 3
unsigned no_e;
unsigned cur_cap;
void* e_array;
}* vector_type;
//for typecasting
#define vector_int_at(v,i) (*((int*)v_at(v,i)))
#define vector_double_at(v,i) (*((double*)v_at(v,i)))
#define vector_char_at(v,i) (*((char*)v_at(v,i)))
void* v_at(vector_type v, iterator i) {
if ( v == NULL )
fail("v_at() Error: no such vector");
if ( i == iterator_end )
i = v->no_e -1;
if ( i < 0 || i >= v->no_e )
fail("v_at() Error: no such element in this vector");
return (v->e_array+i); //return element
}
I want to copy value into the void* e_array
, it can be either integer, character or a double.
void v_push_back(vector_type v, void* new_val){
if ( v->no_e >= v->cur_cap ) {
/*** need to expand the array ***/
v->cur_cap += (v->cur_cap)? v->cur_cap : 2;
v->e_array = check_a(realloc(v->e_array, sizeof(void*) * v->cur_cap));
//allocate memory
}
/*** copy new_val into the array at end position (v->no_e) ***/
printf("%d %d %p\n",v->e_sz,v->no_e,v->e_array+(v->no_e *v->e_sz));
memcpy(
v->e_array +(v->no_e)*v->e_sz,
new_val,
v->e_sz
);
(v->no_e)++;
}
I have called this function like this:
c1 = 'o'; v_push_back(vc1,(void*)&c1); //for character
for ( i1 = 0 ; i1 < 10 ; i1++ ){ //for integer
v_push_back(vi1,(void*)&i1);
}
//I call these like
for ( i1 = 0 ; i1 < vector_size(vi1) ; i1++ )
printf(" %ld",vector_int_at(vi1,i1));
printf("\n");
But it seems things doesn't work for integer but works well for characters but for integers garbage values are copied as shown: enter image description here
Please help me out. thanks
Here the complete project: https://s3.amazonaws.com/assignment.pointers.vectorc.implementation/C-VectorImplementation1.zip