2012-05-11 51 views
3
#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如何使用GNU hcreate_r

如何使用本hcreate_r

和其他問題是:

你能privde GNU擴展C庫的例子? 我覺得GNU擴展C庫的文檔是不夠的知識寫的。

和我有很多關於如何使用擴展C庫的問題。

回答

4

首先,您需要添加#define _GNU_SOURCE宏以正確訪問GNU擴展。即:

#define _GNU_SOURCE 
#include <search.h> 

然後,你需要了解的文件:

功能:INT hcreate_r(爲size_t NEL,結構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) 
+0

嗨violet313,謝謝。代碼起作用。但是htab = calloc(30,sizeof(struct hsearch_data));只是分配內存,沒有初始化爲零。不需要初始化爲0? – wei

+1

啊,那就是[calloc]的美麗(http://linux.die.net/man/3/calloc);它會爲你留下記憶〜* * iff *你的'calloc'實現是幸運的* *月亮已滿*星期四*&*當天你看到喜鵲*&*你的分配很大足夠需要整個頁面,,, *然後它甚至可能比'malloc' +'memset'更快*但是在任何情況下它都少了,因此我喜歡它;) – violet313

+0

爲什麼你不去'struct hsearch_data HTAB; memset(&htab,0,sizeof(htab));結果= hcreate_r(30,&htab);'? –