pete said:
C.K. said:
Given an array of strings (i.e char *strings[10]),
write C code to sort the list in increasing order of string length.
Run time efficiency is a primary concern.
#include <string.h>
#include <stdlib.h>
int compare(const void *arg1, const void *arg2)
{
size_t L1, L2;
L1 = strlen(arg1);
L2 = strlen(arg2);
return L2 > L1 ? -1 : L1 > L2;
}
qsort
(strings, sizeof strings/sizeof *strings, sizeof *strings, compare);
You obviously didn't test this, because that won't work at all.
The const void * arguments qsort passes to the compare function
are pointers to the array elements
- not the array elements themselves.
In this case, they're pointer-to-pointer-to-char,
converted to void *.
In this case, the correct comparison function would be:
int lencomp(const void *a, const void *b)
{
char * const *sa = a;
char * const *sb = b;
size_t alen = strlen(*sa);
size_t blen = strlen(*sb);
return (alen > blen) - (alen < blen);
}