![]() |
![]() |
![]() |
Sort an array
#include <stdlib.h> void qsort( void* base, size_t num, size_t width, int (*compare) ( const void* , const void* ) );
libc
The qsort() function sorts the base array using the comparison function specified by compare.The base argument must have at least num elements, each of width bytes.
The comparison function pointed to by compare is called with two arguments that point to elements in the array. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is less than, equal to, or greater than the second argument.
#include <stdio.h> #include <stdlib.h> #include <string.h> char* some_strs[] = { "last", "middle", "first" }; int compare( const void* op1, const void* op2 ) { const char **p1 = (const char **) op1; const char **p2 = (const char **) op2; return( strcmp( *p1, *p2 ) ); } int main( void ) { qsort( some_strs, sizeof( some_strs ) / sizeof( char * ), sizeof(char *), compare ); printf( "%s %s %s\n", some_strs[0], some_strs[1], some_strs[2] ); return EXIT_SUCCESS; }
produces the output:
first last middle
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | No |
Thread | Yes |
![]() |
![]() |
![]() |