c - sort a 2d array using qsort - seg fault -
i'm trying sort 2d array of strings simplified version looks like, ( dont want change datatype of "namearray" "char *namearray[4]" )
#include <sys/types.h> #include <stdio.h> int cstring_cmp(const void *a, const void *b) { const char **ia = (const char **)a; const char **ib = (const char **)b; return strcasecmp(*ia, *ib); } int test() { char namearray[4][10]={"test","alpha","hyper","city"}; // int nelem = sizeof(namearray)/sizeof(char *); int index = 0; //printf("nelem =%d\n", nelem); for(index=0; index < 4; index++) { printf("-> %s\n", namearray[index]); } qsort( &namearray[0], 4, sizeof(namearray[0]), cstring_cmp); printf("after sort\n"); for(index=0; index < 4; index++) { printf("-> %s\n", namearray[index]); } return 0 ; } ( update: changed i'm directly using value(4) instead of calculating nelem. problem getting qsort working. )
the arguments comparison function pointers, rather pointers pointers.
you don't need cast believe, since parameters void *, can assign them local variables , compiler takes care of them.
try this:
int cstring_cmp(const void *a, const void *b) { const char *ia = a; const char *ib = b; return strcasecmp(ia, ib); } or rid of local variables if don't need them (only need them if you're planning on adding more code comparison function):
int cstring_cmp(const void *a, const void *b) { return strcasecmp(a, b); }
Comments
Post a Comment