2012-03-09 3 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'를 루프로 다시 작성해야합니다. –

+0

예. 일단 완전히 작동하게되면, 지금 당장 작동하기 때문에 그대로 유지할 것입니다. – Mike

+0

'int Jan = 0100;'이것은 8 진 상수입니다. 1 월은 64 진수 (유효하지 않음) – wildplasser

답변

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 *'는 암시 적으로 다른 포인터 타입으로 변환 될 수 있으며 명시 적 캐스트는 미묘한 버그를 숨길 수 있습니다. –

+0

@larsmans : 죄송합니다 - 코드를 작성하고'char *'를'struct date *'로 대체했습니다. 그것을 바꿨습니다. – Zeta

관련 문제