bsort.c 1.13 KB
Newer Older
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
/*
 * Items: bsort(
 * Standardized-By: SuS
 * Not-Detected-by: gcc-4.4.3 + Linux
 */

/* example taken pretty much directly from SuS */

#ifndef __DEHEADER__
#include <stdio.h>
#include <string.h>
#endif
#include <stdlib.h>

#define TABSIZE    1000

struct node {                  /* these are stored in the table */
    char *string;
    int length;
};
struct node table[TABSIZE];    /* table to be searched */

int
node_compare(const void *node1, const void *node2)
{
    return strcoll(((const struct node *)node1)->string,
        ((const struct node *)node2)->string);
}

main(int argc, char **argv)
{
    struct node *node_ptr, node;
    char str_space[20];   /* space to read string into */

    node.string = str_space;
    while (scanf("%s", node.string) != EOF) {
        node_ptr = (struct node *)bsearch((void *)(&node),
               (void *)table, TABSIZE,
               sizeof(struct node), node_compare);
        if (node_ptr != NULL) {
            (void)printf("string = %20s, length = %d\n",
                node_ptr->string, node_ptr->length);
        } else {
            (void)printf("not found: %s\n", node.string);
        }
    }
}