Updated: April 19, 2023 |
Sort an array
#include <stdlib.h> void qsort( void* base, size_t num, size_t width, int (*compare) (const void*, const void* ) );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The qsort() function sorts the base array using the comparison function specified by compare. The array must have at least num elements, each of width bytes.
#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 |