hsearch(3) Library Functions Manual hsearch(3) hcreate, hdestroy, hsearch, hcreate_r, hdestroy_r, hsearch_r - (libc -lc) #include int hcreate(size_t nel); void hdestroy(void); ENTRY *hsearch(ENTRY item, ACTION action); #define _GNU_SOURCE /* feature_test_macros(7) */ #include int hcreate_r(size_t nel, struct hsearch_data *htab); void hdestroy_r(struct hsearch_data *htab); int hsearch_r(ENTRY item, ACTION action, ENTRY **retval, struct hsearch_data *htab); hcreate() hsearch() hdestroy() ( ) . . hcreate_r() hsearch_r() hdestroy_r() . htab . ( ). hcreate(). nel . ( .) . hcreate_r() hcreate() *htab. htab hcreate_r(). hdestroy() hcreate(). hdestroy() hcreate(). hdestroy_r() *htab hcreate_r(). hsearch() item ( "" strcmp(3)) . item ENTRY : typedef struct entry { char *key; void *data; } ENTRY; key . data . action hsearch() . ENTER item ( ) FIND NULL. ( action FIND data.) hsearch_r() hsearch() *htab. hsearch_r() hsearch() *retval . hcreate() hcreate_r() . 0 errno . hsearch() . hsearch() NULL action ENTER action FIND item . hsearch_r() 0 . errno . hcreate_r() hdestroy_r() : EINVAL htab NULL. hsearch() hsearch_r() : ENOMEM action ENTER key . ESRCH action FIND key . POSIX.1 ENOMEM . attributes(7). +--------+------------------------------------+------------------------+ || | | +--------+------------------------------------+------------------------+ |hcreate(),| | MT-Unsafe race:hsearch | |hsearch(),| | | |hdestroy()| | | +--------+------------------------------------+------------------------+ |hcreate_r(),| | MT-Safe race:htab | |hsearch_r(),| | | |hdestroy_r()| | | +--------+------------------------------------+------------------------+ hcreate() hsearch() hdestroy() POSIX.1-2008. hcreate_r() hsearch_r() hdestroy_r() GNU. hcreate() hsearch() hdestroy() SVr4, POSIX.1-2001. hcreate_r() hsearch_r() hdestroy_r() GNU. . nel 25% . hdestroy() hdestroy_r() key data . ( .) ( ) . SVr4 POSIX.1-2001 action ENTER . libc glibc ( glibc 2.3) data key . . 24 . #include #include #include static char *data[] = { "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliet", "kilo", "lima", "mike", "november", "oscar", "papa", "quebec", "romeo", "sierra", "tango", "uniform", "victor", "whisky", "x-ray", "yankee", "zulu" }; int main(void) { ENTRY e; ENTRY *ep; hcreate(30); for (size_t i = 0; i < 24; i++) { e.key = data[i]; /* data is just an integer, instead of a pointer to something */ e.data = (void *) i; ep = hsearch(e, ENTER); /* there should be no failures */ if (ep == NULL) { fprintf(stderr, "entry failed\n"); exit(EXIT_FAILURE); } } for (size_t i = 22; i < 26; i++) { /* print two entries from the table, and show that two are not in the table */ e.key = data[i]; ep = hsearch(e, FIND); printf("%9.9s -> %9.9s:%d\n", e.key, ep ? ep->key : "NULL", ep ? (int) ep->data : 0); } hdestroy(); exit(EXIT_SUCCESS); } bsearch(3) lsearch(3) malloc(3) tsearch(3) 3 . . : . 6.18 8 2026 hsearch(3)