我有一個程序,旨在讀取單詞和拆分它們,分離每個和單獨計數(有標點符號差異的單詞有目的地計爲不同的單詞)。C qsort不排序結構數組
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部分。在這一點上我有點難過。我在這裏做錯了什麼,這是防止這種輸出排序文件? (按字母順序排序)
可能的dup e:http://stackoverflow.com/questions/8451020/sort-array-of-pointers-to-structures-qsort?rq=1 – abligh