user2073752
user2073752

Reputation: 53

Void array, dynamic size variables in C

Alright so i'll try to explain my problem clearly.

I would like to have a function which would sort an array of anything, based on the size of an element and on the offset and the size of the the variable in an element (for use with structures).

So my function would look like:

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

array is a pointer to the beginning of the array

elem_size is the size of one element in the array

elem_count is the count of elements in the array

operand_offset is the offset of the variable within the element to base the sort on (it would be 0 if the element is only one variable, but it could be more if the element is a struct)

operand_size is the size of that variable

In this function i need to create a temp variable, i would do it like that:

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

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

I know i could do it byte per byte, but i would like to know if there is a better way.

So my question is: How to set the "size" of a pointer to elem_size ?

Aditional question: Could i type array[i] to access an element if the size is known ?


EDIT Ok so my problem is solved i must use memcpy

But now i have another problem i didn't expect.

Given the size and the offset of the operand within the element, how could i extract it and 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 i do that?


*EDIT 2: * Well, finally it was too complicated managing an if statement for each size of operand, so i did something completely different

So basically i had a void *array containing n elements, and i was writing a function to sort it.

But instead of giving directly the offset and the size of the operand within the element, i gave the function another function to compare two elements. That 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*));

Upvotes: 1

Views: 1056

Answers (1)

Bill Lynch
Bill Lynch

Reputation: 81916

Couldn't you just use memcpy? That will likely do it in the most efficient manner.

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

Upvotes: 2

Related Questions