How to use the qsort function to sort an array of strings in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static int compare_function(const void *a, const void *b) {
    return strcmp(*(const char**)a, *(const char**)b);
}

int main()
{
    const char *arr[] = {"abdc", "bb", "abcd", "b", "aa", "ab", "aab"};

    int len = sizeof(arr) / sizeof(arr[0]);

    qsort(arr, len, sizeof(const char*), compare_function);

    for (int i = 0; i < len; i++)
        printf("%s\n", arr[i]);

    return 0;
}




/*
run:

aa
aab
ab
abcd
abdc
b
bb

*/

 



answered May 6, 2021 by avibootz
...