排序动态分配的字符串 [英] Sorting dynamically allocated strings

查看:237
本文介绍了排序动态分配的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有奇怪的问题:

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

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

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

这篇关于排序动态分配的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆