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
#
4

1 回答 1

3

C 通过值传递参数,这意味着内部正在更改副本,因此调用者看不到更改。将地址传递给:oid_hashtestadd()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()请注意,不需要转换返回值。

于 2012-10-05T09:49:10.323 回答