当我使用函数时,哈希值为空。为什么?
这是我的代码:

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

最佳答案

C按值传递参数,这意味着oid_hash的副本在testadd()内部被更改,因此调用方看不到更改。将oid_hash的地址传递给testadd()

testadd(&oid_hash);

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

注:返回值malloc()不需要强制转换。

关于c - 从函数返回哈希值时,为什么哈希值是空的?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12743465/

10-11 22:10
查看更多