You want to use the qsort()
function.
qsort(base, num_of_elements, element_size, my_compare);
The comparison function my_compare
takes two arguments, each a const void *
, and returns a number indicating the relative order of the arguments. A negative number means the first argument is before the second argument. A positive number means the first argument is after the second argument. A zero is returned if the arguments have compared to be equal.
As your string comparison is case insensitive, you will need to create your own comparison function, or find one provided to you by your system that is not part of the C library proper. POSIX provides strcasecmp()
for this purpose (Google tells me that _stricmp()
is available on Windows).
int my_compare (const void *a, const void *b) {
return strcasecmp(a, b);
}
Defining the comparison function is usually the trickiest part of using qsort()
. You have to understand the context of the pointers that are being passed into that function. When an array of TYPE
is passed into qsort()
, it will pass a pointer to const TYPE
to each argument of the comparison function.
In your case, you would be passing in an array of array of MAX_CHAR_LEN
char
s. So, each argument to the comparison function is a pointer to const array of MAX_CHAR_LEN
char
s. This means that technically, the my_compare
function should be written like this:
int my_compare (const void *a, const void *b) {
typedef char TYPE[MAX_CHAR_LEN];
const TYPE *aa = (const TYPE *)a;
const TYPE *bb = (const TYPE *)b;
return strcasecmp(*aa, *bb);
}
The cast on the arguments would normally not be necessary, except that C doesn't really support the notion of a constant array. It converts such a thing into an array of constants, so the cast is required to reflect that.
However, the address of an array is equal to the address of its first element. That is, for the code above, the following assertions would be true:
assert(aa == (const void *)*aa);
assert(bb == (const void *)*bb);
So, because the dereference of a pointer to an array equals the decayed address value of the same array, the first implementation of my_compare()
is sufficient for your 2-D array.