用qsort比较字符串

时间:2015-01-13 17:22:14

标签: c

我想从文件中读取n个字符串并按字母顺序对它们进行排序 这是我的代码版本:

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

    char **citireMatrice(int *n)
    {
        char c;
        char sep[] = " ,./;:'[]{}|`~!@#$%^&*()\n";
        char **x=NULL;
        char **aloca=NULL;
        char *valoca=NULL;
        int citireCaracterNormal=0;
        int lungime=0;
        FILE *f = fopen("date.in","r");

    x = (char **)malloc(1*sizeof(char *));
    *n = 1;
    *(x+(*n)-1) = NULL;
    while((c = fgetc(f))!=EOF)
    {
        if(strchr(sep,c))
        {
            if(citireCaracterNormal)
            {
                lungime++;  //adaug '\0' la sfarsit-ul cuvantului
                valoca = (char *)realloc(*(x+(*n)-1),lungime*sizeof(char));
                if(valoca == NULL)
                {
                    printf("Eroare de alocare a memoriei!");
                    exit(1);
                }
                *(x+(*n)-1) = valoca;
                *(*(x + (*n)-1) + lungime -1) = '\0';
                lungime = 0;

                (*n)++;
                aloca = (char **)realloc(x,(*n)*sizeof(char*));
                if(aloca == NULL)
                {
                    printf("Eroare de alocare a memoriei!");
                    exit(1);
                }
                x = aloca;
                *(x+(*n)-1) = NULL;

                citireCaracterNormal = 0;
            }
        }
        else
        {
            lungime++;
            valoca = (char *)realloc(*(x+(*n)-1),lungime*sizeof(char));
            if(valoca == NULL)
            {
                printf("Eroare de alocare a memoriei!");
                exit(1);
            }
            *(x+(*n)-1) = valoca;
            *(*(x + (*n)-1) + lungime - 1) = c;

            citireCaracterNormal = 1;
        }
    }
    (*n)--;
    fclose(f);
    return x;
}

void afisare(char **x,int n)
{
    int i;
    for(i=0;i<n;i++)
        printf("%s\n",*(x+i));
}

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

int main()
{
    int n;
    char **x = citireMatrice(&n);
    afisare(x,n);
    qsort(x,n,sizeof(char *),predicat);
    printf("\n\nDupa sortare:\n\n");
    afisare(x,n);
    return 0;
}

问题在于它没有对它们进行排序。 predicat函数出了什么问题? 参数ab不是x数组的核心地址。

2 个答案:

答案 0 :(得分:2)

传递给qsort(此处predicat)的函数将 指针 带到要比较的每个元素。

由于您要排序的内容为char*,因此您的函数将通过char**

我相信你应该这样改写:

int predicat(const void* a, const void* b)
{
    char* pStrA = *(char**)a;
    char* pStrB = *(char**)b;

    printf("Comparing %s to %s\n", pStrA, pStrB); // To verify you have the right strings.

    return -strcmp(pStrA, pStrB);
}

答案 1 :(得分:0)

predicat的论据不是char const*。他们是char const**。你需要使用:

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

另外,使用

    return -strcmp(*(char const**)a, *(char const**)b);

您将按相反顺序对它们进行排序。我不知道你是否打算那样做。如果没有,请使用

    return strcmp(*(char const**)a, *(char const**)b);