排序动态分配的字符串

时间:2011-02-17 22:09:21

标签: c string qsort

我有一个奇怪的问题:

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]);

符合预期:

before
c
b
a
after
a
b
c

但是

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]);

给出

before
c
b
a
after
b
a
c

为什么字符串排序不正确?

2 个答案:

答案 0 :(得分:2)

qsort比较器函数的参数是指向要比较的参数的指针。我认为你需要一个额外的解除引用。换句话说,a和b不是char *,它们是char **。

答案 1 :(得分:2)

您的比较函数接收数组中项目的地址。你需要取消引用才能获得数组中的指针:

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