2010-03-08 45 views
0

我試圖增加一些特定鍵的值,如果它被發現。出於某種原因,當我從哈希表中轉儲所有keys:values時,我總是得到(指針)地址。GLib散列表 - 指針

Output 
     a: 153654132 // should be 5 
     b: 1 
     c: 153654276 // should be 3 
     d: 1 
     e: 1 
     f: 153654420 // should be 3 


int proc() 
{ 
    struct st stu; 
    gpointer ok, ov; 

    //... some non-related code here 

    if(!g_hash_table_lookup_extended(table, key, &ok, &ov)){ 
     stu.my_int = g_malloc(sizeof(guint)); 
     *(stu.my_int) = 0; 
     g_hash_table_insert(table, g_strdup(key), GINT_TO_POINTER(1)); 
    }else{ 
     stu.my_int = g_malloc(sizeof(guint)); 
     *(stu.my_int)++; 
     g_hash_table_insert(table, g_strdup(key), stu.my_int); 
    } 
} 

任何想法將不勝感激。

+0

FIXED:我取代所述第二插入件爲: (OV )++; g_hash_table_insert(table,g_strdup(key),ov); – Mike 2010-03-08 03:37:25

回答

1

++的優先級高於*。所以你正在增加指針stu.my_int本身,而不是指向它。你可能想要(* stu.my_int)++。

1

我數7個錯誤在8行:

/* 1) ov, the actual value read from the hash table, is never used */ 
if(!g_hash_table_lookup_extended(table, key, &ok, &ov)){ 
    stu.my_int = g_malloc(sizeof(guint)); 
    *(stu.my_int) = 0; 
    /* 2) stu.my_int not freed: memory leak */ 
    g_hash_table_insert(table, g_strdup(key), GINT_TO_POINTER(1)); 
    /* 3) g_strdup(key) not freed: memory leak */ 
}else{ 
    stu.my_int = g_malloc(sizeof(guint)); 
    /* 4) stu.my_int not freed: memory leak */ 
    /* 5) stu.my_int not initialized: stu.my_int contains junk */ 
    *(stu.my_int)++; 
    /* 6) incrementing a pointer, not the value pointed by */ 
    g_hash_table_insert(table, g_strdup(key), stu.my_int); 
    /* 7) g_strdup(key) not freed: memory leak */ 
} 

下面是如何我寫(未測試):

gpointer ov; 
gint value; 

/* ... */ 

if(g_hash_table_lookup_extended(table, key, NULL, &ov)) { 
    value = GPOINTER_TO_INT(ov); 
} else { 
    value = 1; 
} 

g_hash_table_insert(table, key, GINT_TO_POINTER(value)); 
+0

這是非常好的建議。 – geocar 2010-03-09 14:46:26