c - 为什么当我使用 qsort() 对字符串数组进行排序时 qsort() 不起作用?

标签 c sorting

我正在尝试对这个字符串列表进行排序:["a", "z", "b"]。所以答案应该是 ["a", "b", "z"]。但是,当我尝试使用 C 的 qsort() 时,没有任何 Action !我做错了什么?

MWE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int sortcmpfunc (const void *a, const void *b)
{ return strcmp((const char*)a, (const char*)b); }

int main(){
  const char** list = (const char**)malloc(50*sizeof(const char*));
  for(int i = 0; i < 50; i++){
    list[i] = (char*)malloc(50*sizeof(char));
  }

  list[0] ="a";
  list[1] = "z";
  list[2] = "b";

  for (int i=0; i<3; i++){ printf("%s ", list[i]); } printf("\n");
  qsort(list, 3, sizeof(const char*), sortcmpfunc);
  for (int i=0; i<3; i++){ printf("%s ", list[i]); } printf("\n");

  return 0;
}

使用 gcc test-qsort.c && ./a.out 输出:

a z b
a z b

最佳答案

简单

strcmp(*(char **) a, *(char **) b);

请注意,每个元素的指针都会传递给比较函数,因此您需要转换为正确的类型并取消引用。

请避免

for (int i=0; i<3; i++){ printf("%s\n", list[i]); }

而是写

for (int i = 0; i < 3; i++) {
    printf("%s\n", list[i]);
}

太可怕了

还有用

gcc -Wall -Werror test-qsort.c && ./a.out

关于c - 为什么当我使用 qsort() 对字符串数组进行排序时 qsort() 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39812717/

相关文章:

Angular Material 表 : Sorting not working

java - 如何按数字而不是按字母顺序对文件名集合进行排序?

javascript - 根据属性值(int)对对象数组进行排序

c - 数组条目在 C 中被覆盖

c - 使用 EOF(CTRL+D) 重复输入的最后一行

c - 在终端中运行已编译的 GCC 文件时,没有任何反应

algorithm - 是否可以按降序迭代获取数组的部分和?

c - 单片机上的uart软件阅读——代码理解

c - 基本逻辑运算符问题

excel - Excel/SharedStrings 的排序算法