Here is my code:
#include <stdio.h>
#include <string.h>
#include <errno.h>
int cmp(const void *a, const void *b) {
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
}
void print_array(char **array, size_t len) {
size_t i;
for(i=0; i<len; i++) {
printf("%s, ", array[i]);
}
putchar('\n');
}
int main(int argc, char *argv[]) {
char *strings[] = { "z1.doc", "z100.doc", "z2.doc", "z3.doc", "z20.doc"};
size_t strings_len = sizeof(strings) / sizeof(char *);
print_array(strings, strings_len);
qsort(strings, strings_len, sizeof(char *), cmp);
print_array(strings, strings_len);
system("PAUSE");
return 1;
}
the actual output is
z1.doc, z100.doc, z2.doc, z20.doc, z3.doc
and I want it to be
z1.doc, z2.doc, z3.doc, z20.doc, z100.doc
What am doing wrong?
The actual output is correct, the string "z100.doc" is less than "z2.doc". The strcmp compares character by character and when it gets to the '1' that is less than '2' and it stops there, so z100 < z2.
If you name the files z001.doc, z002.doc, z003.doc, z020.doc, z100.doc it will sort the way you want.
Change your comparator to say:
return (atoi(*ib + 1) - atoi(*ia + 1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With