/** * An example of the use of qsort to sort an array of chars * Also, a qsort inspired array printing function. * * @author gtowell * Created: April 2021 * **/ #include #include #include #ifndef NULL #define NULL (void *)0 #endif /** * A comparison function for passing into qsort * This comparison function requires that that array * being sorted just contains characters * @param p -- a pointer to a location in the array * @param q -- a pointer to another location in the array * @return an int describing the relation between p and q * less than 0 if pq, equal 0 is p==q * **/ int compareChar(const void * p, const void * q) { const char *pc = p; const char *qc = q; return *pc - *qc; } /** * A ridiculously complex way to print an array, but reasonably * generic and, even better, it follows qsort * @param base -- a pointer to the start of the array -- or at * least the start of the portion of the array to be printed * @param nmemb -- the number of item in the array (or at least * the number of items to be printed) * @param size -- the number of bytes of the items in the array * @param fmt -- a formatting string * **/ void parray2(void * base, size_t nmemb, size_t size, char* fmt) { for (int i = 0; i < nmemb; i++) { char c = *((char *)base); printf(fmt, c); base += size; } printf("\n"); } /** * Fill an array with random chars, print it, sort it, * print it again * **/ int main(int argc, char const *argv[]) { srand(time(NULL)); char aa[100]; // fill the array with random chars for (int i = 0; i < 100; i++) aa[i] = 'a' + (rand() % 26); parray2(aa, 100, sizeof(char), "%c"); qsort(aa, 100, sizeof(char), compareChar); parray2(aa, 100, sizeof(char), "%c"); return 0; }