pointers - Void array, dynamic size variables in C -



pointers - Void array, dynamic size variables in C -

alright i'll seek explain problem clearly.

i have function sort array of anything, based on size of element , on offset , size of the variable in element (for utilize structures).

so function like:

void sort(void* array, size_t elem_size, int elem_count, size_t operand_offset, size_t operand_size)

array pointer origin of array

elem_size size of 1 element in array

elem_count count of elements in array

operand_offset offset of variable within element base of operations sort on (it 0 if element 1 variable, more if element struct)

operand_size size of variable

in function need create temp variable, that:

void* temp = malloc(elem_size); *temp = *(array+ i*elem_size);

but compiler doesn't agree: dereferencing void* pointer, , doesn't know size of temp variable...

i know byte per byte, know if there improve way.

so question is: how set "size" of pointer elem_size ?

aditional question: type array[i] access element if size known ?

edit ok problem solved must utilize memcpy

but have problem didn't expect.

given size , offset of operand within element, how extract , compare it?

kinda like:

void *a = malloc(operand_size); void *b = malloc(operand_size); memcpy(a, array+i*elem_size + operand_offset, operand_size); memcpy(b, array+j*elem_size + operand_offset, operand_size); if (a < b) ... else ...

how can that?

*edit 2: * well, complicated managing if statement each size of operand, did different

so had void *array containing n elements, , writing function sort it.

but instead of giving straight offset , size of operand within element, gave function function compare 2 elements. works well

int comparechar(void* a, void* b); int compareshort(void* a, void* b); int compareint(void* a, void* b); int comparelong(void* a, void* b); int comparefoo(void* a, void* b); void sort(void* array, size_t elem_size, int elem_count, int (*compare)(void*,void*));

couldn't utilize memcpy? in efficient manner.

uint8_t* temp = malloc(elem_size); memcpy(temp, array + * elem_size, elem_size);

c pointers void

Comments

Popular posts from this blog

javascript - mongodb won't find my schema method in nested container -

How do you set up a perforce server to work over the internet? -

ios - Lagging ScrollView with UIWebview inside -