简体   繁体   English

如何按字母顺序对指针数组进行排序,然后使用qsort?

[英]How to sort an array of pointers in alphabetical order, and then use qsort?

I am trying to write a function in which I sort the pointers inside of wptrs , an array of pointers to strings in another array. 我正在尝试编写一个函数,在其中我对wptrs内的指针进行排序, wptrs是指向另一个数组中的字符串的指针数组。 I am challenging myself not to use string.h for this exercise, as I want to understand how a sorting algorithm could work in C. I am using qsort() , however, but I am trying to write a comparison function for it called mycharptrcompare() . 我要挑战自己不要在本练习中使用string.h,因为我想了解排序算法如何在C中工作。但是我正在使用qsort() ,但是我正尝试为其编写比较函数mycharptrcompare()

I have looked at how strcmp() works, and I have tried to mimic that with mycharptrcompare() . 我研究了strcmp()工作方式,并尝试使用mycharptrcompare()来模仿。 However, I notice the difference that strcmp() expects a char*, while the mycharptrcompare() function expects a char**. 但是,我注意到strcmp()期望使用char *,而mycharptrcompare()函数期望使用char **的mycharptrcompare() I've written a method called dumpwptrs to show me the contents and how they are organized within wptrs . 我已经编写了一种称为dumpwptrs的方法,以向我展示内容及其在wptrs中的组织wptrs Thus far, I have the following code: 到目前为止,我有以下代码:

UPDATE: 更新:

I have also tried: 我也尝试过:

int mycharptrcompare(const void *a, const void *b)
{
  //Need to convert a void * to a more specific type to dereference
  const char *aPtr = a;
  const char *bPtr = b;
  const char **pa = &aPtr;
  const char **pb = &bPtr;

  while (*pa && *pa == *pb) {
    pa++;
    pb++;
  }
  return *pa - *pb;
}

and my output I got was: 我得到的输出是:

(null) (空值)

jumps 跳跃

world 世界

is

dog

blue 蓝色

Which is still incorrect, because my list should be sorted in alphabetical order, and the first input (the word "hello"), has not been read in. 这仍然是不正确的,因为我的列表应按字母顺序排序,并且第一个输入(单词“ hello”)尚未被读入。

FYI here is an example use of qsort() . 仅供参考,这里是qsort()的示例用法。

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

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

int main(void)
{
    char *wptrs[] = { "hello", "jumps", "world", "is", "dog", "blue" };
    size_t len = sizeof wptrs / sizeof wptrs[0];
    qsort(wptrs, len, sizeof wptrs[0], cmp);

    for(size_t i = 0; i < len; i++) {
        printf("%s\n", wptrs[i]);
    }
    return 0;
}

Program output: 程序输出:

blue
dog
hello
is
jumps
world

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

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