c - 对动态分配的字符串进行排序

标签 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

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

最佳答案

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

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

关于c - 对动态分配的字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5035289/

相关文章:

c++ - 如何调用带参数的外部程序?

将字母 append 到文件末尾的 C 程序

c - Qsort 及其问题

c - 打印给定文本文件中最常出现的单词,无法在 C 中按频率排序

C:使用 qsort 对二维数组进行逐行排序

c - 我需要一个简短的不稳定建议来理解这个代码过程

c: strtod:双指针与对单指针的引用

c - *char 值在函数上改变

python - 类型错误 : Format Requires Mapping

string - 获取不带字符的字符串的所有子串的时间复杂度是多少?