About qsort() in C, difference between ** buf and buf[][]

后端 未结 2 1139
没有蜡笔的小新
没有蜡笔的小新 2021-01-16 13:59

When I use qsort() in the C on my Mac, these code works well, It can sort every lines in one file well.

int compare(const void *p, const void *q) {
    retur         


        
2条回答
  •  鱼传尺愫
    2021-01-16 14:04

    When you attempt to qsort buf declared as char **buf, you are using the wrong comparison function. As I noted in the comment, char buf[x][y] is an x array of character arrays of y chars, e.g. char (*)[y] when passed as a parameter. When you declare buf as char **buf;, you declare a pointer to a pointer to type char. In either case, you have a pointer to string, and you must dereference each value passed to qsort one additional level of indirection., e.g.

    int cmpstrings (const void *a, const void *b) {
        return strcmp (*(char * const *)a, *(char * const *)b);
    }
    

    A short example using char **buf; would be:

    #include 
    #include 
    #include 
    
    /* qsort string comparison - for pointer to pointer to char */
    int cmpstrings (const void *a, const void *b) {
        return strcmp (*(char * const *)a, *(char * const *)b);
    }
    
    int main (void) {
    
        char *ap[] = { "This is a tale",
                        "of captian Jack Sparrow",
                        "a pirate so brave",
                        "on the seven seas." },
            **buf = NULL;
        int n = sizeof ap/sizeof *ap;    
    
        if (!(buf = malloc (n * sizeof *buf))) { /* allocate pointers */
            fprintf (stderr, "error: virtual memory exhausted.\n");
            return 1;
        }
    
        for (int i = 0; i < n; i++)
            buf[i] = strdup (ap[i]);    /* allocate/copy strings */
    
        qsort (buf, n, sizeof *buf, cmpstrings);
    
        for (int i = 0; i < n; i++) {   /* print and free */
            printf ("buf[%d] : %s\n", i, buf[i]);
            free (buf[i]);
        }
        free (buf);
    
        return 0;
    }
    

    Example

    $ ./bin/qsortptp
    buf[0] : This is a tale
    buf[1] : a pirate so brave
    buf[2] : of captian Jack Sparrow
    buf[3] : on the seven seas.
    

提交回复
热议问题