HP C/iX Library Reference Manual (30026-90004)

Chapter 5 373
HP C/iX Library Function Descriptions
tsearch
NOTE
The tsearch() function and the header file <search.h> are not part of ANSI
C. Using them makes your program less portable.
Examples
The following code reads in strings and stores structures containing a pointer to each
string and a count of its length. It then walks the tree, printing out the stored strings and
their lengths in alphabetical order.
#include <search.h>
#include <stdio.h>
struct node { /* pointers to these are stored in the tree */
char *string;
int length;
};
char string_space[10000]; /* space to store strings */
struct node nodes[500]; /* nodes to store */
struct node *root = NULL; /* this points to the root */
main( )
{
char *strptr = string_space;
struct node *nodeptr = nodes;
void print_node( ), twalk( );
inti=0,node_compare( );
while (gets(strptr) != NULL i++ 500) {
/* set node */
nodeptr->string = strptr;
nodeptr->length = strlen(strptr);
/* put node into the tree */
(void) tsearch((char *)nodeptr, root,
node_compare);
/* adjust pointers, so we don't overwrite tree */
strptr += nodeptr->length + 1;
nodeptr++;
}
twalk(root, print_node);
}
/* This function compares two nodes, based on an
alphabetical ordering of the string field. */
int
node_compare(node1, node2)
struct node *node1, *node2;
{