I am creating a C dynamic array library, sort of. Please note that I do this for fun in my free time, so please do not recommend millions of existing libraries.
I started to sort. An array has the size of an arbitrary element, defined as a struct:
typedef struct { //[PRIVATE] Pointer to array data void *array; //[READONLY] How many elements are in array size_t length; //[PRIVATE] How many elements can further fit in array (allocated memory) size_t size; //[PRIVATE] Bytes per element size_t elm_size; } Array;
I originally prepared this to start with the sort function:
void array_sort(Array* a, int(*comparator)(const void*, const void*, size_t)) { if(comparator == NULL) comparator = &memcmp;
However, I found out about qsort
:
void qsort (void* base, size_t num, size_t size, int (*compar)(const void*,const void*));
Apparently, I could just pass my internal array to qsort
. I could just call it:
qsort (a->array, a->length, a->elm_size, comparator_callback);
But there is a signature for the catch comparator, qsort
, which reads:
int (*compar)(const void*,const void*)
So far, memcmp
signature:
int memcmp ( const void * ptr1, const void * ptr2, size_t type_size );
The element size is missing in the qsort
callback, that is, I can no longer have a general comparator function when NULL
is passed as a callback. I could manually create comparators up to X bytes in element size, but that sounds ugly.
Can qsort
(or other built-in sorting) be used with memcpy
? Or do I need to choose between the built-in comparator and the built-in sort function?