2012-03-22 30 views
0

我已经创建了一个结构数组,并且我想使用qsort对它们进行排序以按字母顺序排序日期到字符串月份或我应该说char月份[]。我怎么能使下面的代码显示一个月的结构。请指教。感谢如何在C编程中使用qsort对结构进行排序

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'?文档解释了你需要做的事情,并举​​例说明如何使用它。 – 2012-03-22 17:40:07

回答

3

您可以定义自己的比较排序http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/

所以为整数排序,你会使用

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; 
} 

我想你可以从制作自己的比较器功能。

+0

如果它是一个字符,我想比较 – user1254916 2012-03-22 22:06:17

+0

strcmp的字符串,或者您可以使用><或== – Bram 2012-03-23 08:10:25

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 */ 
     ... 
} 

手册页的例子,然后

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

亲爱的你可以请更具体。我如何在我的代码中使用cmp方法,然后如何使用Qsort。你可以给我举例使用我发布的代码 – user1254916 2012-03-22 18:16:58

+0

什么是* p1和* p2指向 – user1254916 2012-03-22 18:18:12

相关问题