C qsort不对结构数组进行排序

时间:2014-04-08 21:21:56

标签: c arrays sorting structure

我有一个程序,旨在读取单词并将它们分开,将每个单独分开并单独计数(带有标点差异的单词有意计为不同的单词)。

typedef struct word
{
    char letters[100];
    int count;
} Word;

int compare (const void *a, const void *b)
{
    return strcmp((*(struct word **) a)->letters,(*(struct word **) b)->letters);
}

int main()
{
    int sizeCheck = 0;
    Word ** collection = malloc(sizeof(Word*));
    Word * array = malloc(sizeof(Word));

    FILE *fptr, *fout;
    char fileName[80];
    char fileNameWords[80];
    char wordLine[100];
    strcpy(fileName,"data");
    strcpy(fileNameWords,fileName);
    strcat(fileNameWords,"data.out.txt");

行动开始时,假设打开文件一切正常(为简洁起见而删除):

            int wordExists = 0;
            int t1 = 0;
            char tw1[100];


            fscanf(fptr,"%s",wordLine);
            strcpy(array->letters,wordLine);
            array->count = 1;
            collection[sizeCheck] = array;
            sizeCheck++;

            while (!feof(fptr))
            {
                wordExists = 0;
                fscanf(fptr,"%s",wordLine);
                for (t1 = 0; (t1 < sizeCheck) && (wordExists == 0); t1++)
                {
                    strcpy(tw1,array[t1].letters);
                    if (strcmp(tw1,wordLine) == 0)
                    {
                        array[t1].count += 1;
                        wordExists = 1;
                    }
                }
                if (!wordExists)
                {
                    collection = realloc(collection,(sizeCheck+1)*sizeof(Word*));
                    array = realloc(array,(sizeCheck+1)*sizeof(Word));
                    strcpy(array[sizeCheck].letters,wordLine);
                    array[sizeCheck].count = 1;
                    collection[sizeCheck] = array;
                    sizeCheck++;
                }
            }

            qsort(collection,sizeCheck,sizeof(Word*),compare);

            for (t1 = 0; t1 < sizeCheck; t1++)
            {
                fprintf(fout,"%s - %d\n",array[t1].letters,array[t1].count);
            }
            free(collection);
        }
    }
    fclose(fptr);
    fclose(fout);
    return 0;
}

使用指针指针方法,它大部分都有效,除了qsort函数或底部附近的fprintf部分。在这一点上,我有点难过。我在这里做错了什么阻止它输出一个排序文件? (按字母顺序排序)

1 个答案:

答案 0 :(得分:3)

仅对collection数组(指针数组)进行排序。它们指向的值(array的元素)保持不变。由于您fprintf的元素array,您将看不到任何更改。

如果您想对array进行排序,可以使用qsort

进行排序
qsort(array, sizeCheck, sizeof(Word), compareWord);

其中compareWord

int compareWord(const void *a, const void *b) {
    const Word *wa = a;
    const Word *wb = b;
    return strcmp(a->letters, b->letters);
}

或者,只需打印collection而不是array中的元素:

fprintf(fout, "%s - %d\n", collection[t1]->letters, collection[t1]->count);