如何使用GNU hcreate_r [英] how to use the GNU hcreate_r

查看:170
本文介绍了如何使用GNU hcreate_r的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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库的文档知识不足,无法编写.

Could you privde the GNU extension C library examples ? I think the document of GNU extension C library is not enough knowledge to write.

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

and I have many questions of how to use the extension C library .

推荐答案

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

First off, you will need to add the #define _GNU_SOURCE macro in order to access the GNU extensions properly. ie:

#define _GNU_SOURCE
#include <search.h>

然后,您需要了解文档:

Then you need to understand the documentation:

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

Function: 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不同, you 提供了哈希表数据结构.此外,这些结构应初始化为零.因此,您可能想要执行以下操作:


So unlike hcreate, you are providing the hashing table data structures. Further, those structures should be initialised to zero. So then you probably want to do something like this:

//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)

这篇关于如何使用GNU hcreate_r的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆