2012-03-22 17 views
0

構造体の配列を作成しました。qsortを使用して日付を日付順にソートするか、char month []を記述する必要があります。どのように私は次のコードを月に応じて構造体を表示させることができます。ご意見をお聞かせください。おかげCプログラミングでqsortを使用してStructをソートする方法

struct dates 
{ 
    int index; 
    int day; 
    int year; 
    char month[15]; 
}; 


int i=0; 
int count = 0 ; 
char test ='\0'; 
int total =0; 

printf("Please enter the number of dates you need to display"); 
scanf("%d",&total); 
struct dates *ip[total]; 

for(count =0; count< total; count++){ 
    ip[count] = (struct dates*)malloc(sizeof(struct dates)); 

    printf("\nEnter the name month."); 
    scanf("%s", ip[count]->month); 

    printf("\nEnter the Day."); 
    scanf("%d",&ip[count]->day); 

    printf("\nEnter the Year."); 
    scanf("%d", &ip[count]->year);      
} 

for(i=0; i<total; i++){ 
    printf("%s %d %d\n\n",ip[i]->month,ip[i]->day,ip[i]->year); 
} 
+3

あなたは男のqsort' 'を見たことがありますか?ドキュメンテーションはあなたがしなければならないことを説明し、それを使用する方法の例を示します。 –

答えて

3

あなたは私はあなたがそれから独自のコンパレータ機能を作ることができると思うので、あなたが

int intcomp(void *a, void *b){ 
    int *_a = (int *)a; 
    int *_b = (int *)b; 

    if(*_a > *_b) return -1; 
    if(*_a == *_b) return 0; 
    return 1; 
} 

を使用する整数をソートするhttp://www.cplusplus.com/reference/clibrary/cstdlib/qsort/

をソートするために、独自のコンパレータを定義することができます。

+0

文字列の場合は – user1254916

+0

strcmpを比較したい文字であれば<>または<=> – Bram

3

例はqsort

static int 
cmp(const void *p1, const void *p2) 
{ 
     int y1 = ((const struct dates*)p1)->year; 
     int y2 = ((const struct dates*)p2)->year; 

     if (y1 < y2) 
      return -1; 
     else if (y1 > y2) 
      return 1; 

     /* years must be equal, check months */ 
     ... 
} 

のmanページにありますし、その後

qsort(dates, total, sizeof(*dates), cmp); 
+0

を使用できます。より具体的にお聞かせください。私のコードではどのように私はcmpメソッドを使用し、私はどのようにQsortを使用するのですか?私が掲示したコードを使用して私に例を与えることができます – user1254916

+0

* p1と* p2は何を指していますか – user1254916

関連する問題