代码之家  ›  专栏  ›  技术社区  ›  lindelof

qsort(3)的手册页对吗?

  •  4
  • lindelof  · 技术社区  · 14 年前

    手册页 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 . 现在 是指向字符指针的指针,也可以将其视为指向字符的指针表。

    cmpstringp 是指向字符的指针,而不是“指向指向字符的指针”?

    3 回复  |  直到 14 年前
        1
  •  7
  •   Thomas Pornin    14 年前

    回调函数作为参数传递给 qsort() 指向 要比较的两个值。如果你对 char * (例如。 argv[] )那么这些值是 (指向 char 烧焦 .

        2
  •  2
  •   pmg    14 年前
    strcmp(* (char * const *) p1, * (char * const *) p2)
           ^^^^^^^^^^^^^^^^^^^^^
    

    所以 p1 * (char * const *) 或者,去掉 (char * const) char *const 赋值是否与 char * ,所以没问题:-)

        3
  •  0
  •   Oliver Charlesworth    14 年前

    qsort 具体如下:

    qsort(&argv[0], argc, sizeof(char*), cmpstringp);
    

    i、 你给它一个指向元素的指针,元素是 const char *