2016-10-02 8 views
0

["a"、 "z"、 "b"]という文字列のリストをソートしようとしています。答えは["a"、 "b"、 "z"]でなければなりません。しかし、私がCのqsort()を使用しようとすると、何も動きません!私は間違って何をしていますか?文字列の配列をソートするときにqsort()が動作しないのはなぜですか?

MWE:gcc test-qsort.c && ./a.out

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

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

int main(){ 
    const char** list = (const char**)malloc(50*sizeof(const char*)); 
    for(int i = 0; i < 50; i++){ 
    list[i] = (char*)malloc(50*sizeof(char)); 
    } 

    list[0] ="a"; 
    list[1] = "z"; 
    list[2] = "b"; 

    for (int i=0; i<3; i++){ printf("%s ", list[i]); } printf("\n"); 
    qsort(list, 3, sizeof(const char*), sortcmpfunc); 
    for (int i=0; i<3; i++){ printf("%s ", list[i]); } printf("\n"); 

    return 0; 
} 

出力:ので、各要素へのポインタは、比較関数に渡されることを

a z b 
a z b 

答えて

2

単に

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

ノート、あなたがする必要があります正しいタイプと逆参照にキャストします。

そして

for (int i=0; i<3; i++){ printf("%s\n", list[i]); } 

を避けてください、代わりにそれは恐ろしい

だとも恐ろしい:)ウル

gcc -Wall -Werror test-qsort.c && ./a.out 
+0

を使用していただきありがとうございます

for (int i = 0; i < 3; i++) { printf("%s\n", list[i]); } 

を書きます –

関連する問題