2011-02-17 84 views
1

我有奇怪的問題:排序分配字符串

int cmp(const void *a, const void *b) { 
    const char *ia = (const char *) a; 
    const char *ib = (const char *) b; 
    return strcmp(ia, ib); 
} 

char ** names = NULL; 
if((names = (char **) calloc(3,sizeof(char*))) == NULL) 
{ 
    fprintf(stderr,"Unable to allocate the memory"); 
    return 1; 
} 

...

names[0] = "c"; 
names[1] = "b"; 
names[2] = "a"; 
printf("before\n"); 
printf("%s\n",names[0]); 
printf("%s\n",names[1]); 
printf("%s\n",names[2]); 
qsort(names,3,sizeof(char *),cmp); 
printf("after\n"); 
printf("%s\n",names[0]); 
printf("%s\n",names[1]); 
printf("%s\n",names[2]); 

給出預期:

before 
c 
b 
a 
after 
a 
b 
c 

names[0] = (char *) calloc(1024,sizeof(char)); 
names[1] = (char *) calloc(1024,sizeof(char)); 
names[2] = (char *) calloc(1024,sizeof(char)); 
scanf("%s",names[0]); 
scanf("%s",names[1]); 
scanf("%s",names[2]); 
printf("before\n"); 
printf("%s\n",names[0]); 
printf("%s\n",names[1]); 
printf("%s\n",names[2]); 
qsort(names,3,sizeof(char *),cmp); 
printf("after\n"); 
printf("%s\n",names[0]); 
printf("%s\n",names[1]); 
printf("%s\n",names[2]); 

給出

before 
c 
b 
a 
after 
b 
a 
c 

爲什麼字符串沒有正確排序?

回答

2

您的比較函數接收數組中項目的地址。您需要取消引用以獲取陣列中的指針:

int cmp(const void *a, const void *b) { 
    const char *ia = *(const char **) a; 
    const char *ib = *(const char **) b; 
    return strcmp(ia, ib); 
} 
2

qsort比較函數的參數是指向被比較參數的指針。我認爲你需要額外的解除引用。換句話說,a和b不是char *,它們是char **。