1QSORT(3) Linux Programmer's Manual QSORT(3)
2
3
4
6 qsort - sorts an array
7
9 #include <stdlib.h>
10
11 void qsort(void *base, size_t nmemb, size_t size,
12 int(*compar)(const void *, const void *));
13
15 The qsort() function sorts an array with nmemb elements of size size.
16 The base argument points to the start of the array.
17
18 The contents of the array are sorted in ascending order according to a
19 comparison function pointed to by compar, which is called with two
20 arguments that point to the objects being compared.
21
22 The comparison function must return an integer less than, equal to, or
23 greater than zero if the first argument is considered to be respec‐
24 tively less than, equal to, or greater than the second. If two members
25 compare as equal, their order in the sorted array is undefined.
26
28 The qsort() function returns no value.
29
31 SVr4, 4.3BSD, C89, C99.
32
34 Library routines suitable for use as the compar argument include alpha‐
35 sort(3) and versionsort(3). To compare C strings, the comparison func‐
36 tion can call strcmp(3), as shown in the example below.
37
39 For one example of use, see the example under bsearch(3).
40
41 Another example is the following program, which sorts the strings given
42 in its command-line arguments:
43
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47
48 static int
49 cmpstringp(const void *p1, const void *p2)
50 {
51 /* The actual arguments to this function are "pointers to
52 pointers to char", but strcmp(3) arguments are "pointers
53 to char", hence the following cast plus dereference */
54
55 return strcmp(* (char * const *) p1, * (char * const *) p2);
56 }
57
58 int
59 main(int argc, char *argv[])
60 {
61 int j;
62
63 if (argc < 2) {
64 fprintf(stderr, "Usage: %s <string>...\n", argv[0]);
65 exit(EXIT_FAILURE);
66 }
67
68 qsort(&argv[1], argc - 1, sizeof(char *), cmpstringp);
69
70 for (j = 1; j < argc; j++)
71 puts(argv[j]);
72 exit(EXIT_SUCCESS);
73 }
74
76 sort(1), alphasort(3), strcmp(3), versionsort(3)
77
79 This page is part of release 3.25 of the Linux man-pages project. A
80 description of the project, and information about reporting bugs, can
81 be found at http://www.kernel.org/doc/man-pages/.
82
83
84
85 2009-09-15 QSORT(3)