2 .\" Copyright 1993 David Metcalfe (david@prism.demon.co.uk)
4 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
6 .\" References consulted:
7 .\" Linux libc source code
8 .\" Lewine's _POSIX Programmer's Guide_ (O'Reilly & Associates, 1991)
11 .\" Modified 1993-03-29, David Metcalfe
12 .\" Modified 1993-07-24, Rik Faith (faith@cs.unc.edu)
13 .\" 2006-01-15, mtk, Added example program.
14 .\" Modified 2012-03-08, Mark R. Bannister <cambridge@users.sourceforge.net>
15 .\" and Ben Bacarisse <software@bsb.me.uk>
16 .\" Document qsort_r()
18 .TH qsort 3 (date) "Linux man-pages (unreleased)"
20 qsort, qsort_r \- sort an array
23 .RI ( libc ", " \-lc )
26 .B #include <stdlib.h>
28 .BI "void qsort(void " base [. size " * ." nmemb "], size_t " nmemb ", \
30 .BI " int (*" compar ")(const void [." size "], \
31 const void [." size ]));
32 .BI "void qsort_r(void " base [. size " * ." nmemb "], size_t " nmemb ", \
34 .BI " int (*" compar ")(const void [." size "], \
35 const void [." size "], void *),"
36 .BI " void *" arg ");"
40 Feature Test Macro Requirements for glibc (see
41 .BR feature_test_macros (7)):
51 function sorts an array with \fInmemb\fP elements of
53 The \fIbase\fP argument points to the start of the
56 The contents of the array are sorted in ascending order according to a
57 comparison function pointed to by \fIcompar\fP, which is called with two
58 arguments that point to the objects being compared.
60 The comparison function must return an integer less than, equal to, or
61 greater than zero if the first argument is considered to be respectively
62 less than, equal to, or greater than the second.
63 If two members compare as equal,
64 their order in the sorted array is undefined.
68 function is identical to
70 except that the comparison function
72 takes a third argument.
73 A pointer is passed to the comparison function via
75 In this way, the comparison function does not need to use global variables to
76 pass through arbitrary arguments, and is therefore reentrant and safe to
83 functions return no value.
85 For an explanation of the terms used in this section, see
91 Interface Attribute Value
97 T} Thread safety MT-Safe
106 POSIX.1-2001, C89, SVr4, 4.3BSD.
111 To compare C strings, the comparison function can call
113 as shown in the example below.
115 For one example of use, see the example under
118 Another example is the following program,
119 which sorts the strings given in its command-line arguments:
121 .\" SRC BEGIN (qsort.c)
128 cmpstringp(const void *p1, const void *p2)
130 /* The actual arguments to this function are "pointers to
131 pointers to char", but strcmp(3) arguments are "pointers
132 to char", hence the following cast plus dereference. */
134 return strcmp(*(const char **) p1, *(const char **) p2);
138 main(int argc, char *argv[])
141 fprintf(stderr, "Usage: %s <string>...\en", argv[0]);
145 qsort(&argv[1], argc \- 1, sizeof(char *), cmpstringp);
147 for (size_t j = 1; j < argc; j++)