我有一个2级哈希表,解释为here(uthash),有两个不同的结构,声明如下。散列结构b通过散列结构a中的参数d保存s个值及其频率的总计数(为了更好地理解,请看下面的设计)。
update函数应该是这样工作的:如果第一次遇到s,将其添加到struct myb中,并将其添加到struct mya中。如果它已经在struct myb中,则检查是否第一次遇到它的d值,以防将它添加到struct mya中,否则递增它的值。
然而,当我运行代码时,它将第一次遇到的d值保存在hash struct mya中(在本例中是递增的),但我不会在相同的s值上添加收到的其他d值……代码中有什么问题?
d1:3 d2:5
/ /
s1 - d2:4 s2 - d4:3
\ \
d3:1 d5:2
---------------------------
#include <stdio.h>
#include <string.h>
#include "uthash.h"
struct a{
int x;
int count;
UT_hash_handle hh;
};
struct b{
char s[24];
int total;
struct a *mya;
UT_hash_handle hh;
};
void update(struct b **myb, const char *s, u_int32_t d){
struct b *pb;
HASH_FIND_STR(*myb, s, pb);
if(pb == NULL) {
pb = (struct b*)malloc(sizeof(struct b));
if(!pb) return;
strncpy(pb->s, s, sizeof(pb->s));
pb->total = 1;
pb->mya = NULL;
HASH_ADD_STR(*myb, s, pb);
struct a *pa = (struct a*)malloc(sizeof(struct a));
if(!pa) return;
pa->x = d;
pa->count = 1;
HASH_ADD_INT(pb->mya, x, pa);
}
else{
struct a *pp=NULL;
pb->total++;
HASH_FIND_INT(pb->mya, &d, pp);
if(pp == NULL){
pp = (struct a*)malloc(sizeof(struct a));
if(!pp) return;
pp->count = 1;
HASH_ADD_INT(pb->mya, x, pp);
}
else pp->count++;
}
}
void printAll(struct b *myb){
struct b *pb, *tmp;
struct a *pa, *tmp2;
int i = 0, j = 0;
HASH_ITER(hh, myb, pb, tmp) {
i++;
printf("%d) %s: %u\n", i, pb->s, pb->total);
HASH_ITER(hh, pb->mya, pa, tmp2) {
j++;
printf("\t%d) %u: %u\n", j, pa->x, pa->count);
}
j = 0;
}
}
struct b *myb = NULL;
int main(int argc, char **argv ){
char str[10][24] = {"abc","abc","def","abc","hij","def","hij","def","abc","hij"};
int values[10] = {10, 10, 9, 8, 5, 2, 6, 2, 5, 5};
int i;
for(i=0; i<10; i++)
update(&myb,str[i],values[i]);
printf("hash table\n");
printAll(myb);
return 0;
}https://stackoverflow.com/questions/44572176
复制相似问题