2012-10-05 52 views
1

當我的函數,我的散列是空的。爲什麼?爲什麼我的散列從函數返回時是空的?

這是我的代碼:

#include <stdio.h> 
#include <string.h> 
#include "uthash.h" 
struct oid_struct { 
    char descr[20]; 
    char oid[50]; 
    UT_hash_handle hh; 
}; 

testadd(struct oid_struct* oid_hash){ 

struct oid_struct *element; 
element=(struct oid_struct*) malloc(sizeof(struct oid_struct)); 

strcpy(element->descr, "foo"); 
strcpy(element->oid, "1.2.1.34"); 
HASH_ADD_STR(oid_hash, descr, element); 
printf("Hash has %d entries\n",HASH_COUNT(oid_hash)); 

} 


main(){ 
     struct oid_struct *oid_hash = NULL, *lookup; 
     testadd(oid_hash); 
     printf("Hash has %d entries\n",HASH_COUNT(oid_hash)); 

} 

這裏是輸出:

# gcc hashtest.c 
# ./a.out 
Hash has 1 entries 
Hash has 0 entries 
# 
+0

你可以發佈'HASH_ADD_STR()'? – hmjd

+0

它在http://uthash.sourceforge.net/ 中定義,我只是通過這裏提供的結構體來實現uthash。 – roegi

回答

3

下用值傳遞參數,這意味着拷貝的oid_hash被內部testadd()所以變化變呼叫者無法看到。合格oid_hashtestadd()地址:

testadd(&oid_hash); 

void testadd(struct oid_struct** oid_hash) 
{ 
    *oid_hash = element; /* Depending on what is going on 
          inside HASH_ADD_STR(). */ 
} 

注意不需要的malloc()返回值的鑄件。

+0

嗨! thx爲您的及時答案!它現在有效! 只是爲了更好地理解它 - 如果我將一個指針作爲參數傳遞給一個函數 - 我當然將它作爲一個值傳遞,但它仍然指向正確的結構?! – roegi

相關問題