qsort的陷阱

问:求大神解释这个C程序,为什么在compare_strings中使用return strcmp(p, q);就无法正确排序

 1 #include <string.h>
 2 #include <stdlib.h>
 3 
 4 static int compare_strings(const void *p, const void *q);
 5 
 6 void test_qsort_2() {
 7     char *strings[] = {"b", "d", "a", "c"};
 8     qsort(strings, 5, sizeof(strings[0]), compare_strings);
 9     int i = 0;
10     i++;
11     i++;
12     i++;
13     i++;
14 }
15 
16 static int compare_strings(const void *p, const void *q) {
17     return strcmp(*(char**)p, *(char**)q);
18 }

答:qsort传给compare_strings的不是strings[i],而是strings+i,也就是char**,因为转换成了void*,再被strcmp当成char*用,所以无法正确工作,所以解决方法是先把void*转换为char**,在取一次*操作,就成了char*

参考cplusplus.com的文档:

The sorting algorithm used by this function compares pairs of elements by calling the specified compar function with pointers to them as argument.

posted @ 2014-10-28 00:46  rldts  阅读(202)  评论(0编辑  收藏  举报