假设您想使用qsort
对int
数组进行排序。
int numbers[] = {10, 50, 35, 62, 22};
首先,您需要创建一个可以比较两个int
的函数。
int intCompare(void* p1, void* p2)
{
int n1 = *(int*)p1;
int n2 = *(int*)p2;
return (n1 < n2);
}
那么,您可以使用:
qsort(numbers, 5, sizeof(int), intCompare);
当将
numbers
传递给
qsort
时,它会被衰减为
int*
并作为
void*
传递。当我们需要从
intCompare
中的
void*
提取数字时,我们需要将其强制转换为
int*
,然后再解除指针引用并比较值。
以字符串为例,如果您想要排序:
char* strings[] = { "abc", "xyz", "def" };
调用
qsort
的代码将是:
qsort(strings, 3, sizeof(char*), scmp);
当将字符串传递给qsort时,它会被降级为char **并作为void *传递。由qsort传递给scmp的指针的基础类型将是char **,而不是char *。因此,使用如下内容是正确的:
int scmp(const void *p1, const void * p2)
{
char *v1, *v2;
v1 = *(char **) p1;
v2 = *(char **) p2;
return strcmp(v1,v2);
}
第一个版本有时会因为幸运的巧合而正常工作。以下是一个示例程序,展示了一些第一个版本无法正常工作的情况,而第二个版本应该始终能够正常工作。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int scmp1(const void *p1, const void * p2)
{
char *v1, *v2;
v1 = (char *) p1;
v2 = (char *) p2;
return strcmp(v1,v2);
}
int scmp2(const void *p1, const void * p2)
{
char *v1, *v2;
v1 = *(char **) p1;
v2 = *(char **) p2;
return strcmp(v1,v2);
}
void test1()
{
char* strings[] = { "abc", "xyz", "def" };
qsort(strings, 3, sizeof(char*), scmp1);
for( int i = 0; i < 3; ++i )
{
printf("%s\n", strings[i]);
}
printf("\n");
}
void test2()
{
char* strings[] = { "abc", "xyz", "def" };
qsort(strings, 3, sizeof(char*), scmp2);
for( int i = 0; i < 3; ++i )
{
printf("%s\n", strings[i]);
}
printf("\n");
}
void test3()
{
char** strings = malloc(3*sizeof(char*));
strings[0] = "abc";
strings[1] = "xyz";
strings[2] = "def";
qsort(strings, 3, sizeof(char*), scmp1);
for( int i = 0; i < 3; ++i )
{
printf("%s\n", strings[i]);
}
free(strings);
printf("\n");
}
void test4()
{
char** strings = malloc(3*sizeof(char*));
strings[0] = "abc";
strings[1] = "xyz";
strings[2] = "def";
qsort(strings, 3, sizeof(char*), scmp2);
for( int i = 0; i < 3; ++i )
{
printf("%s\n", strings[i]);
}
free(strings);
printf("\n");
}
int main()
{
test1();
test2();
test3();
test4();
}
输出(使用gcc 4.8.4):
abc
xyz
def
abc
def
xyz
abc
xyz
def
abc
def
xyz
scmp("hello", "hello");
只有第一个版本会起作用:http://ideone.com/P96Wmj - mchp1
和p2
是什么,但第二个函数是在比较 char*(字符串)数组时应该用作qsort()
中的比较函数。 - francis