开发者

qsort() works in one direction, but not other

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 w开发者_如何学JAVAay (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 than sizeof(buffer) (and include string.h of course). You also don't need to divide by sizeof(char) since the sizeof function is defined in terms of char-sized units.


If your initial buffer starts off filled with an ordinary C string, which has only a single null terminator at the end, and you want it to end up that way, then you can just exclude the last spot from the sort:

qsort(buffer, strlen(buffer), 1, charCompare);


If you have a buffer that contains '\0' characters and you want them to not end up at the start of the buffer, just make sure '\0' sorts to the end of the array:

int charCompare(const void* ptr1, const void* ptr2)
{
   int c1 = *(char*)ptr1;
   int c2 = *(char*)ptr2;

   if (c1 == 0) c1 = INT_MAX;
   if (c2 == 0) c2 = INT_MAX;

   return c1 - c2;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜