qsort_s
Go Up to stdlib.h Index
Header File
stdlib.h
Category
Searching and sorting utilities
Prototype
errno_t qsort_s(void * __base, rsize_t __nelem, rsize_t __width, int (_USERENTRY *__fcmp)(const void *k, const void *y, void *__context), void *__context);
Description
Replaces qsort adding security enhancements.
qsort_s is an implementation of the "median of three" variant of the quicksort algorithm. qsort_s sorts the entries in a table by repeatedly calling the user-defined comparison function pointed to by __fcmp.
- __base points to the base (0th element) of the table to be sorted.
- __nelem is the number of entries in the table.
- __width is the size of each entry in the table, in bytes.
__fcmp, the comparison function, must be used with the _USERENTRY calling convention.
- fcmp accepts two arguments, k and y, each a pointer to an entry in the table. __context is passed directly to the __fcmp function in order to allow a more generic user implementation. The comparison function compares each of the pointed-to items (*k and *y), and returns an integer based on the result of the comparison.
__fcmp returns an integer that takes its values as follows:
- < 0 if *k < *y
- == 0 if *k == *y
- > 0 if *k > *y
Return Value
qsort_s return zero if successful, otherwise it returns a nonzero value.
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sort_function( const void *a, const void *b, void* context);
char list[5][4] = { "cat", "car", "cab", "cap", "can" };
int main(void)
{
int x;
qsort_s((void *)list, 5, sizeof(list[0]), sort_function, NULL);
for (x = 0; x < 5; x++)
printf("%s\n", list[x]);
return 0;
}
int sort_function( const void *a, const void *b, void* context)
{
return( strcmp((char *)a,(char *)b) );
}
Portability
| POSIX | Win32 | ANSI C | ANSI C++ |
|---|---|---|---|
|
+ |
+ |
+ |
+ |