c - Sorting dynamically allocated strings -


i've got strange problem:

int cmp(const void *a, const void *b) {    const char *ia = (const char *) a;    const char *ib = (const char *) b;    return strcmp(ia, ib); }  char ** names = null; if((names = (char **) calloc(3,sizeof(char*))) == null) {    fprintf(stderr,"unable allocate memory");    return 1; } 

...

names[0] = "c"; names[1] = "b"; names[2] = "a"; printf("before\n"); printf("%s\n",names[0]); printf("%s\n",names[1]); printf("%s\n",names[2]); qsort(names,3,sizeof(char *),cmp); printf("after\n"); printf("%s\n",names[0]); printf("%s\n",names[1]); printf("%s\n",names[2]); 

gives expected:

before c b after b c 

but

names[0] =  (char *) calloc(1024,sizeof(char)); names[1] =  (char *) calloc(1024,sizeof(char)); names[2] =  (char *) calloc(1024,sizeof(char)); scanf("%s",names[0]); scanf("%s",names[1]); scanf("%s",names[2]); printf("before\n"); printf("%s\n",names[0]); printf("%s\n",names[1]); printf("%s\n",names[2]); qsort(names,3,sizeof(char *),cmp); printf("after\n"); printf("%s\n",names[0]); printf("%s\n",names[1]); printf("%s\n",names[2]); 

gives

before c b after b c 

why strings not sorted correctly?

your comparison function receives address of item in array. need dereference pointer in array:

int cmp(const void *a, const void *b) {    const char *ia = *(const char **) a;    const char *ib = *(const char **) b;    return strcmp(ia, ib); } 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -