简体   繁体   English

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

[英]Why doesn't qsort() work when I use it to sort an array of strings?

I'm trying to sort this list of strings: ["a", "z", "b"]. 我正在尝试对以下字符串列表进行排序:[“ a”,“ z”,“ b”]。 So the answer should be ["a", "b", "z"]. 因此答案应该是[“ a”,“ b”,“ z”]。 However, when I try to use C's qsort(), nothing moves! 但是,当我尝试使用C的qsort()时,没有任何动作! What am I doing wrong? 我究竟做错了什么?

MWE: 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;
}

Output with gcc test-qsort.c && ./a.out : gcc test-qsort.c && ./a.out输出:

a z b
a z b

Simply 只是

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

note that a pointer to each element is passed to the comparison function, hence you need to cast to the correct type and dereference. 请注意,指向每个元素的指针将传递给比较函数,因此您需要强制转换为正确的类型和取消引用。

And please avoid 而且请避免

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

and instead write 然后写

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

it's horrible 这太糟糕了

And also use 并使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM