4
#include <stdio.h>
#include <stdlib.h>
#include <search.h>
#include <assert.h>

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, **ep;
    struct hsearch_data *htab;
    int i;
    int resultOfHcreate_r;
    resultOfHcreate_r=hcreate_r(30,htab);
    assert(resultOfHcreate_r!=0);
    hdestroy_r(htab);
    exit(EXIT_SUCCESS);
}

错误hcreate_r

这个怎么用hcreate_r

另一个问题是:

您能否提供 GNU 扩展 C 库示例?我认为GNU扩展C库的文档知识不够写。

我有很多关于如何使用扩展 C 库的问题。

4

1 回答 1

5

首先,您需要添加#define _GNU_SOURCE宏才能正确访问 GNU 扩展。IE:

#define _GNU_SOURCE
#include <search.h>

然后你需要了解文档:

功能: int hcreate_r (size_t nel, struct hsearch_data *htab)

The hcreate_r function initializes the object pointed to by htab to contain a 
hashing table with at least nel elements. So this
function is equivalent to the hcreate function except that the
initialized data structure is controlled by the user.

This allows having more than one hashing table at one time. 
The memory necessary for the struct hsearch_data object can be allocated
dynamically. It must be initialized with zero before calling this
function.

The return value is non-zero if the operation was successful. 
If the return value is zero, something went wrong, which probably means
the programs ran out of memory.


因此,与 不同的是hcreate提供的是散列表数据结构。此外,这些结构应初始化为零。那么你可能想做这样的事情:

//dynamically create a single table of 30 elements 
htab=calloc(1,sizeof(struct hsearch_data));
resultOfHcreate_r=hcreate_r(30,htab);

//do some stuff

//dispose of the hash table and free heap memory
hdestroy_r(htab);
free(htab)
于 2012-05-11T14:52:05.737 回答