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_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()必要ないことに注意してください。

于 2012-10-05T09:49:10.323 に答える