zoukankan      html  css  js  c++  java
  • [skill][c] *(char**)

    /* 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 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).

    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.

    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.

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


    http://stackoverflow.com/questions/10364153/pointer-cast-for-use-with-qsort

    http://stackoverflow.com/questions/13487821/the-use-of-char/13487867

  • 相关阅读:
    第五,六章
    第三,四章
    第一,二章
    20131019作业 2 分支、循环结构
    20131016课堂实验4
    20131014课堂实验3
    20131007国庆作业例7-11,7-12,7-13,7-14
    20131006国庆作业例7-7,7-8,7-9
    20131006国庆作业例7-4,7-5,7-6
    20131006国庆作业第七章例7-1,7-2,7-3
  • 原文地址:https://www.cnblogs.com/hugetong/p/6567836.html
Copyright © 2011-2022 走看看