How can I combine two arrays declared as void pointers?

I currently have a program that I am writing where I am implementing a Mergesort array. The array has unknown variables - it is a pointer to the void, so I actually do not know which objects I sort (there is a comparison function that passed for actual comparisons).

How can I traverse an array when it is a pointer to void? I found out that I cannot just use a typical array format (i.e. arr[3]), as it is a pointer to void. There is a parameter passed to my functions that contains the size of the mystery elements, so I suppose I need it. Is there a way that I could use it depending on the size provided, so I CAN use this typical array format, or do I need to use pointer arithmetic (again, to somehow apply it to a specific size)?

Thanks to everyone who makes any contribution! :)

+4
source share
2 answers

There is a parameter passed to my functions that contains the size of the mystery elements

- , . , qsort.

void merge_sort(void *array, size_t N, size_t size, int (*compare)(const void *, const void *));

void* char*, i :

size_t size; // Element size
void *array; // The address of the array
size_t N;    // Count of elements in the array
char *base = array;
for (int i = 0 ; i != N ; i++) {
    void *elementAtPositionI = &base[i * size];
    ...
}

, , :

void *secondHalf = &base[N * size / 2];

, ... , !

:

  • , : , num_elem/2, num_elem/2+1, num_elem . num_elem/2 num_elem-num_elem/2 . , , ( ).
  • , . : merge(carr, carr + (num_elem/2) /* <<== HERE */, num_elem/2, num_elem/2, elem_size, cmp);
  • helper. helper[helper_place * elem_size] = *a_temp; memcpy elem_size . , .

.

+2

mergesort char*. , , .

void mergesort(void* a, void* b, size_t objectSize, size_t objectCount)
{
   char* ac = (char*)a;
   char* bc = (char*)b;

   //.....

   mergesort(ac, ac+objectSize*objectCount/2);
}
+1

Source: https://habr.com/ru/post/1538943/


All Articles