달력

4

« 2024/4 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
2008. 2. 17. 22:50

bsearch() 삽질예방/표준 API2008. 2. 17. 22:50

qsort에 이어 매우 유용한 서치 api, 물론 stdlib.h만 필요하다.

원형
       #include <stdlib.h>

       void *bsearch(const void *key, const void *base, size_t nel,
              size_t width, int (*compar)(const void *, const void *));

qsort와 거의같지만, 찾고자 하는 key변수가 추가 되었다.  못찾으면 NULL을 리턴한다.(매우 직관적이지 아니한가.)

코드
int IntCmpAsc(const void* a, const void* b);

int main(void)
{
    int a[10];
    int key;    // to find

    int* p;

    for (int i = 0; i < 10; i++)
        printf("%10p ", &a[i]);
    putchar('\n');
    for (int i = 0; i < 10; i++)
        printf("%10d ", a[i] = i);
    putchar('\n');

    key = 9;
    p = (int*)bsearch(&key, a, 10, sizeof(int), IntCmpAsc);

    if (p == NULL)
        printf("couldn't find.\n");
    else
        printf("found = %d, %p\n", *p, p);

    printf("\n");
    return 0;
}

int IntCmpAsc(const void* a, const void* b)
{
    return *(int*)a - *(int*)b;
}


결과
0xbf8cff6c 0xbf8cff70 0xbf8cff74 0xbf8cff78 0xbf8cff7c 0xbf8cff80 0xbf8cff84 0xbf8cff88 0xbf8cff8c 0xbf8cff90
         0          1          2          3          4          5          6          7          8          9
found = 9, 0xbf8cff90



복잡한 숫자들은 배열의 주소와 포인터값이다.

:
Posted by Kwang-sung Jun