This is how I made my comparison function to pass to qsort():
int charCompare(const void* ptr1, const void* ptr2)
{
char c1 = *(char*)ptr1;
char c2 = *(char*)ptr2;
return c1 - c2;
}
And this is the implementation:
char buffer[SIZE];
/*
* buffer filled here
*/
qsort(buffer, sizeof(buffer)/sizeof(char), sizeof(char), charCompare);
printf("%s", buffer);
Nothing gets printed. I’m pretty sure it’s because the null characters are coming before the regular characters, since it works the other way (if I return c2-c1 instead from charCompare). But how would I go about getting rid of the null characters, since I want it to be in order from a to z, not the other way around?
You are exactly right that the null(s) are getting included. You are sorting the entire buffer, not just the part that contains your (null terminated) string. You need to use
strlen(buffer)rather thansizeof(buffer)(and includestring.hof course). You also don’t need to divide bysizeof(char)since thesizeoffunction is defined in terms ofchar-sized units.