[英]Why is my hash empty when returning it from a function?
當我的功能,我的哈希是空的。 為什么?
這是我的代碼:
#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通過值傳遞參數,這意味着在testadd()
更改了oid_hash
的副本 ,因此更改對調用者是不可見的。 將oid_hash
的地址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()
的返回值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.