Given that you don't know the type you can use memcmp
as suggested by @pmg.
#include <string.h>
//...
int compare(void* a,void* b, size_t size)
{
return memcmp(a, b, size);
}
In the size
argument you'd want to pass the size of the larger object if their size is different, like for instance, two strings of different length.
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
Return value:
<0
the first byte that does not match in both memory blocks has a lower value in ptr1 than in ptr2 (if evaluated as unsigned char values).
0
the contents of both memory blocks are equal.
>0
the first byte that does not match in both memory blocks has a greater value in ptr1 than in ptr2 (if evaluated as unsigned char values)
You can specify different return values if you'd like but these seem to match pretty well with what you need if you're not boud to specifically -1, 0 and 1.
Sample use case:
int x = 10;
int y = 20;
int res = compare(&x, &y, sizeof x);
res
value will be <0
, -1
most likely.
When you know the types simply recast those back to whatever the type of the arguments you pass to the function, let's say those are int
's:
//...
if(*(int*)a < *(int*)b)
{
return -1;
}
else if(*(int*)a < *(int*)b)
//...
Note that if this is to use as qsort
compare function it does not apply because one of the arguments of qsort
is precisely the type size, so you would need a compare function for each type you want to compare.