qsort(3) 的联机帮助页正确吗?
qsort(3)
库例程的联机帮助页给出了对命令行上作为参数给出的单词进行排序的示例。比较函数的内容如下:
static int
cmpstringp(const void *p1, const void *p2)
{
/* The actual arguments to this function are "pointers to
pointers to char", but strcmp(3) arguments are "pointers
to char", hence the following cast plus dereference */
return strcmp(* (char * const *) p1, * (char * const *) p2);
}
但这里排序的是argv
的元素。现在argv是一个指向字符指针的指针,它也可以被视为一个指向字符的指针表。
因此它的元素是指向字符的指针,所以 cmpstringp
的实际参数不应该是指向字符的指针,而不是“指向字符指针的指针”吗?
The manpage of the qsort(3)
library routine gives an example of sorting the words given as arguments on the command-line. The comparison function reads as follows:
static int
cmpstringp(const void *p1, const void *p2)
{
/* The actual arguments to this function are "pointers to
pointers to char", but strcmp(3) arguments are "pointers
to char", hence the following cast plus dereference */
return strcmp(* (char * const *) p1, * (char * const *) p2);
}
But what's being sorted here are the elements of argv
. Now argv
is a pointer to pointers of chars, which can be viewed also as a table of pointers to chars.
Hence its elements are pointers to chars, so shouldn't the actual arguments of cmpstringp
be pointers to chars, and not "pointers to pointers to char"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
作为参数传递给
qsort()
的回调函数是用指向要比较的两个值的指针作为参数来调用的。如果对char *
数组(例如argv[]
)进行排序,则值为char *
(指向char
的指针) code>) 并且比较函数将接收指向这些值的指针,即指向char
的指针。The callback function passed as argument to
qsort()
is called with, as arguments, pointers to the two values to compare. If you sort an array ofchar *
(e.g.argv[]
) then the values arechar *
(pointers tochar
) and the comparison function will receive pointers to such values, i.e. pointers to pointers tochar
.因此
p1
的类型为* (char * const *)
或者通过删除 * 的(char * const)
;并且char *const
的赋值与char *
兼容,所以没问题:-)So
p1
is of type* (char * const *)
or, by removing *'s(char * const)
; andchar *const
is assignment compatible withchar *
, so no problem :-)不,因为您可能会按如下方式调用
qsort
:即向它传递一个指向元素的指针,并且元素是一个
const char *
。No, because presumably you would call
qsort
as follows:i.e. you pass it a pointer-to-element, and an element is a
const char *
.