如何在C中对指向char的指针数组进行排序? [英] How to qsort an array of pointers to char in C?

查看:35
本文介绍了如何在C中对指向char的指针数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 C 中有一个指向 char 的指针数组:

Suppose I have an array of pointers to char in C:

char *data[5] = { "boda", "cydo", "washington", "dc", "obama" };

我希望使用 qsort 对这个数组进行排序:

And I wish to sort this array using qsort:

qsort(data, 5, sizeof(char *), compare_function);

我无法想出比较功能.出于某种原因,这不起作用:

I am unable to come up with the compare function. For some reason this doesn't work:

int compare_function(const void *name1, const void *name2)
{
    const char *name1_ = (const char *)name1;
    const char *name2_ = (const char *)name2;
    return strcmp(name1_, name2_);
}

查了很多资料,发现不得不在qsort里面使用**:

I did a lot of searching and found that I had to use ** inside of qsort:

int compare_function(const void *name1, const void *name2)
{
    const char *name1_ = *(const char **)name1;
    const char *name2_ = *(const char **)name2;
    return strcmp(name1_, name2_);
}

这行得通.

谁能解释一下这个函数中 *(const char **)name1 的用法?我完全不明白.为什么是双指针?为什么我原来的功能不起作用?

Can anyone explain the use of *(const char **)name1 in this function? I don't understand it at all. Why the double pointer? Why didn't my original function work?

谢谢,博达·西多.

推荐答案

如果它有助于保持头脑清醒,那么您应该在比较器中强制转换指针的类型与数据指针的原始类型相同你传入 qsort(qsort 文档称之为 base).但是要使 qsort 成为通用的,它只是将所有内容作为 void* 处理,而不管它真正"是什么.

If it helps keep things straight in your head, the type that you should cast the pointers to in your comparator is the same as the original type of the data pointer you pass into qsort (that the qsort docs call base). But for qsort to be generic, it just handles everything as void*, regardless of what it "really" is.

因此,如果您正在对整数数组进行排序,那么您将传入一个 int*(转换为 void*).qsort 会给你两个 void* 指向比较器的指针,你将它们转换为 int*,并取消引用以获得你的 int 值实际比较.

So, if you're sorting an array of ints, then you will pass in an int* (converted to void*). qsort will give you back two void* pointers to the comparator, which you convert to int*, and dereference to get the int values that you actually compare.

现在用 char* 替换 int:

如果你正在对一个char*的数组进行排序,那么你将传入一个char**(转换为void*).qsort 将返回两个 void* 指向比较器的指针,您将其转换为 char**,并取消引用以获取 char* 值你实际上比较.

if you're sorting an array of char*, then you will pass in a char** (converted to void*). qsort will give you back two void* pointers to the comparator, which you convert to char**, and dereference to get the char* values you actually compare.

在您的示例中,因为您使用的是数组,所以您传入的 char**char* 数组衰减"到指向其第一个元素的指针.由于第一个元素是 char*,指向它的指针是 char**.

In your example, because you're using an array, the char** that you pass in is the result of the array of char* "decaying" to a pointer to its first element. Since the first element is a char*, a pointer to it is a char**.

这篇关于如何在C中对指向char的指针数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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