Defined in header <stdlib.h> | ||
(1) | ||
errno_t qsort_s(void* ptr, rsize_t count, rsize_t size, int(*comp)(constvoid*,constvoid*,void*), | (2) | (since C11) |
qsort_s
is only guaranteed to be available if__STDC_LIB_EXT1__ is defined by the implementation and if the user defines__STDC_WANT_LIB_EXT1__ to the integer constant1 before including<stdlib.h>.Ifcomp indicates two elements as equivalent, their order in the resulting sorted array is unspecified.
Contents |
ptr | - | pointer to the array to sort |
count | - | number of elements in the array |
size | - | size of each element in the array in bytes |
comp | - | comparison function which returns a negative integer value if the first argument isless than the second, a positive integer value if the first argument isgreater than the second and zero if the arguments are equivalent. The signature of the comparison function should be equivalent to the following: int cmp(constvoid*a,constvoid*b); The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array. |
context | - | additional information (e.g., collating sequence), passed tocomp as the third argument |
Despite the name, neither C nor POSIX standards require this function to be implemented usingquicksort or make any complexity or stability guarantees.
Unlike other bounds-checked functions,qsort_s
does not treat arrays of zero size as a runtime constraint violation and instead returns successfully without altering the array (the other function that accepts arrays of zero size isbsearch_s).
The implementation ofqsort_s
in theWindows CRT is incompatible with the C standard. The Microsoft's versionis declared as:void qsort_s(void*base,size_t num,size_t width,
int(*compare)(void*,constvoid*,constvoid*),void* context);.It does not return a value, and the comparison function has a reversed parameter order with regard to the standard: thecontext is passed first.
#include <limits.h>#include <stdio.h>#include <stdlib.h> int compare_ints(constvoid* a,constvoid* b){int arg1=*(constint*)a;int arg2=*(constint*)b; if(arg1< arg2)return-1;if(arg1> arg2)return1;return0; // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut // return arg1 - arg2; // erroneous shortcut: undefined behavior in case of// integer overflow, such as with INT_MIN here} int main(void){int ints[]={-2,99,0,-743,2,INT_MIN,4};int size=sizeof ints/sizeof*ints; qsort(ints, size,sizeof(int), compare_ints); for(int i=0; i< size; i++)printf("%d ", ints[i]); printf("\n");}
Output:
-2147483648 -743 -2 0 2 4 99
(C11) | searches an array for an element of unspecified type (function)[edit] |
C++ documentation forqsort |