2012-03-09 66 views
0

固定。bsearch結構中的多個項目

包括

main() 
{ 
    int n; 
    int i; 
    char tempMonth[255]; //Used to store the month until checked 

    scanf("%d", &n); 

    struct date *list; 

    list = (struct date *)malloc((n * sizeof(struct date))); 

    for(i = 0; i < n; i++) 
    { 
     scanf("%s %d %d", tempMonth, &list[i].day, &list[i].year); 
     list[i].month = getMonth(tempMonth); 
    } 

    convertFullYear(list, n); 

    qsort(list, n, sizeof(struct date), (compfn)sortDates); 

    convertSmallYear(list, n); 

    for(i = 0; i < n; i++) 
    { 
     printf("%s %d %02d\n", months[list[i].month], list[i].day, list[i].year); 
    } 

    char *pos = (char*) bsearch(Jan, list, sizeof(list), sizeof(Jan), findJan); 
} 

正如你可以看到我已經把我的想法是正確的調用bsearch,但是如果這是正確的我不知道在哪裏可以從這裏走。

+2

注意:你應該重寫'getMonth'作爲循環。 – 2012-03-09 13:09:32

+0

是的,一旦我得到它充分運作我會這樣做,只是保持它,因爲它現在的作品 – Mike 2012-03-09 13:11:02

+0

'int Jan = 0100;'請注意,這是一個八進制常數。 Jan將是64位十進制(這是無效的) – wildplasser 2012-03-09 13:28:58

回答

1

如果你正在尋找一個特定的日期,然後用struct date作爲重點:

struct date Jan; 
Jan.month = 0; 
Jan.year = 00; 
Jan.day = 1; 

然後你可以使用你的sortDates功能(你應該把它重命名爲compareDates):

struct date* pos = bsearch(
    &Jan, /* pointer to the structure above */ 
    list, /* pointer to your array */ 
    n, /* number of elements in your array */ 
    sizeof(struct date), /* size of each element */ 
    (compfn)sortDates /* compare function */ 
); 

另見http://www.cplusplus.com/reference/clibrary/cstdlib/bsearch/http://en.cppreference.com/w/cpp/algorithm/bsearch作爲進一步的例子。

+0

不需要轉換'bsearch'的返回值;一個'void *'可以隱式轉換爲任何其他指針類型,而一個顯式的轉換可能會隱藏細微的錯誤。 – 2012-03-09 14:08:44

+0

@larsmans:糟糕 - 只需c&p他的代碼,用'struct date *'替換'char *'。改變了它。 – Zeta 2012-03-09 14:10:34