NAME
qsort, qsort_r - sort an array
SYNOPSIS
#include <stdlib.h>
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
void qsort_r(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *, void *), void *arg);
DESCRIPTION
The qsort() function sorts an array with nmemb elements of size size. The base argument points to the start of the array.
The contents of the array are sorted in ascending order according to a comparison function pointed to by compar, which is called with two arguments that point to the objects being compared.
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined.
The qsort_r() function is identical to qsort() except that the comparison function compar takes a third argument. A pointer is passed to the comparison function via arg. In this way, the comparison function does not need to use global variables to pass through arbitrary arguments, and is therefore reentrant and safe to use in threads.
RETURN VALUE
The qsort() and qsort_r() functions return no value.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int cmp(const void *a, const void *b)
{
return strcmp((char* )a, (char* )b);
}
int main(int argc, char** argv)
{
char a[6][6] = {"bbb", "cccc", "cc", "eeeee", "aaab", "ddddda"};
qsort((void*)a, 6, sizeof(a[0]), cmp);
for(int i=0; i<6; i++)
{
printf("%s\n", a[i]);
}
return 0;
}
运行结果
jl@jl-virtual-machine:~/test$ ./a.out
aaab
bbb
cc
cccc
dddddaeeeee
eeeee
本文详细介绍了C语言标准库中的排序函数qsort和qsort_r,包括它们的使用语法、功能以及如何定义比较函数。通过一个字符串数组排序的示例,展示了qsort函数的使用,排序后打印出结果。qsort_r函数增加了传递额外参数的能力,使其在多线程环境中更安全。
3万+

被折叠的 条评论
为什么被折叠?



