Sort an array of strings in C

This example program demonstrates sorting an array using qsort.

/* "qsort" is declared in stdlib.h. */
#include <stdlib.h>
#include <stdio.h>
/* string.h declares "strcmp". */
#include <string.h>

/* "array" is an unsorted shopping list. */

const char * array[] = {
    "eggs",
    "bacon",
    "cheese",
    "mushrooms",
    "spinach",
    "potatoes",
    "spaghetti",
};

/* n_array is the number of elements in the array. */

#define n_array sizeof(array)/sizeof(const char *)

/* Compare the strings. */

static int compare (const void * a, const void * b)
{
    /* The pointers point to offsets into "array", so we need to
       dereference them to get at the strings. */

    return strcmp (*(const char **) a, *(const char **) b);
}

int main ()
{
    int i;
    qsort (array, n_array, sizeof (const char *), compare);
    for (i = 0; i < n_array; i++) {
        printf ("%d: %s.\n", i, array[i]);
    }
    return 0;
}

(download)

It outputs the following:

0: bacon.
1: cheese.
2: eggs.
3: mushrooms.
4: potatoes.
5: spaghetti.
6: spinach.


Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer