Array-strings sorted using qSort in C

早过忘川 提交于 2019-12-11 14:24:47

问题


the question is simple: there is some way that the ordered array that returns me the "qsort", is returned in reverse, ie I want to avoid the use of any auxiliary array to invest the resulting array using qsort.

this is my code, which reads from standard input strings to be sorted, and uses a comparison function for sorting.

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <string.h>

            int cstring_cmp(const void *a, const void *b)
            {
                const char **ia = (const char **)a;
                const char **ib = (const char **)b;
                return strcasecmp(*ia, *ib);
                /* strcmp functions works exactly as expected from
                comparison function */
            }

Thanks in advance for your response, sorry for my English

            int main (int argc, char *argv [])

            {
            int number;
            char temp [4000];

            printf("input number: ");
            scanf("%d",&number);

            char* array_string [number];
            int i;
            for (i=0;i<number;i++) {
            scanf(" %[^\n]", temp);
            array_string [i] = (char*)malloc((strlen(temp)+1)*sizeof(char));
            strcpy(array_string[i], temp);
            }


            size_t large = sizeof(array_string) / sizeof(char *);
            qsort(array_string,large ,sizeof(char *) ,cstring_cmp );
            printf ("\n");
            printf ("the sorted array list is:\n");
            for (i=0;i<large;i++)
            printf("%s\n", array_string [i]);
                    return 0;
            }

回答1:


Does this do what you want?

        int cstring_cmp(const void *a, const void *b)
        {
            const char **ia = (const char **)a;
            const char **ib = (const char **)b;
            return -strcasecmp(*ia, *ib);
            /* return the negative of the normal comparison */
        }



回答2:


Have you just tried reversing the order of parameters to strcasecmp?

return strcasecmp(*ib, *ia);



来源:https://stackoverflow.com/questions/4061217/array-strings-sorted-using-qsort-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!