指针转换为与qsort一起使用 [英] Pointer cast for use with qsort

查看:92
本文介绍了指针转换为与qsort一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码段手写内容是从我正在阅读的书中复制的:

This code snippet hand copied from a book I am reading:

/* scmp: string compare of *p1 and *p2 */
int scmp(const void *p1, const void *p2)
{
        char *v1, *v2;
        v1 = *(char **) p1; 
        v2 = *(char **) p2; 

        return strcmp(v1, v2);
}

此函数与qsort一起用于对字符串数组进行排序.我不明白的是,为什么用v1 = *(char **) p1;而不是v1 = (char *) p1;还是行不通的? v1 = p1;?我猜编译器应该自动类型转换该设置.甚至考虑一下:

This function is used with qsort to sort an array of strings. The point I don't understand is, why v1 = *(char **) p1; instead of just v1 = (char *) p1; or wouldn't even this work; v1 = p1;? I guess compiler should automatically typecast that assigment. Or even, consider this:

/* scmp: string compare of *p1 and *p2 */
int scmp(const void *p1, const void *p2)
{
        return strcmp(p1, p2);
}

我认为(我可能是非常错误的)编译器应该将p1p2类型转换为char *,因为这正是strcmp(char *, char *)的期望.

I think (I might be awfully wrong) compiler is supposed to typecast p1 and p2 into char * since it's what strcmp(char *, char *) expects.

总而言之,问题是为什么v1 = *(char **) p1?

To sum up, the question is why v1 = *(char **) p1 ?

推荐答案

qsort将要比较的元素的指针传递给比较函数;由于在C中没有模板,因此该指针只是残酷地转换为const void *(C中的void *只是表示这是某种指针",要对其执行操作,必须将其转换为实际指针).类型).

qsort passes to the comparing function a pointer to the elements it has to compare; since in C there are no templates, this pointer is just brutally cast to a const void * (void * in C just means "this is some kind of pointer", and to do something on it you must cast it back to its actual type).

现在,如果您要对字符串数组进行排序,则必须比较的每个元素都是一个char *;但是qsort向每个元素传递一个 pointer 到比较函数,因此您的scmp接收的实际上是一个char **(一个指向字符串第一个字符的指针),强制转换为const void *的原因是比较功能的签名如此.

Now, if you are sorting an array of strings, each element you have to compare is a char *; but qsort passes to the comparison function a pointer to each element, so what your scmp receives is actually a char ** (a pointer to a pointer to the first character of the string), casted to a const void * because the signature of the comparison function says so.

因此,要获取char *,必须首先将参数转换为其实际类型(char **),然后取消引用此指针以获得要比较的实际char *.

So, to get your char *, you have first to convert the parameters to their actual type (char **), and then dereference this pointer to get the actual char * you want to compare.

(尽管从const正确性的角度来看,将其强制转换为const char **会更正确)

(although, it would be more correct from a const-correctness point of view to cast to const char **)

这篇关于指针转换为与qsort一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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