开发者

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 to allocate the 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 as expected:

before
c
b
a
after
a
b
c

But

names[0] =  (char *) calloc(1024,sizeof(char));
names[1] =  (ch开发者_JAVA百科ar *) 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
a
after
b
a
c

Why strings are not sorted correctly?


Your comparison function receives the address of the item in the array. You need to dereference that to get the pointer in the 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);
}


The qsort comparator function's arguments are pointers to the arguments being compared. I think you need an additional dereference. In other words, a and b are not char*, they are char**.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜