glib hash tables



Hi all,

I'm having trouble understanding the GHashTable and it's member
functions.

I've made the following simple code for testing purposes:

#include <stdio.h>
#include <glib.h>

typedef struct _client
{
        guint           id;
        guint           win;
        gchar           *name;
        gchar           *number;
        gboolean        mute;
} client ;

static void print_hash_kv (gpointer key, gpointer value, gpointer
user_data)
{
        gchar   *i = (gchar *) key;
        client  *d = (client *) value;
        
        printf ("<-- %s -> %d , %s, %s in %d.\n", i, d->id, d->name, d->number,
d->win);
}

int main (int argc, char **argv)
{
        client          *c, *d;
        GHashTable      *hash = g_hash_table_new (g_str_hash, g_str_equal); 

        if ((c = g_new (client, 1)) == NULL)
        {
                printf ("unable to alloc c");
                return 1;
        }
                
        c->id = 2;
        c->win = 3;
        c->name = g_strdup ("client1");
        c->number = g_strdup ("0123456789");
        c->mute = TRUE;
        
        printf ("--> %d , %s, %s in %d.\n", c->id, c->name, c->number, c->win);
        
        g_hash_table_insert (hash, g_strdup ("2"), c);
        
        g_free (c);

        hash = g_hash_table_ref (hash);

        if ((d = g_new (client, 1)) == NULL)
        {
                printf ("unable to alloc d");
                return 1;
        }

        d->id = 1;
        d->win = 2;
        d->name = g_strdup ("client2");
        d->number = g_strdup ("9876543210");
        d->mute = FALSE;
        
        printf ("--> %d , %s, %s in %d.\n", d->id, d->name, d->number, d->win);
        
        g_hash_table_insert (hash, g_strdup ("1"), d);
                
        g_free (d);

        printf ("done inserting..... \n");

        g_hash_table_foreach (hash, print_hash_kv, NULL);

        return 0;
}

The thing is that the output is quite annoying:
--> 2 , client1, 0123456789 in 3. 
--> 1 , client2, 9876543210 in 2.
done inserting.....
<-- 1 -> 0 , client2, 9876543210 in 2.
<-- 2 -> 0 , client2, 9876543210 in 2.

My question is how do I manage to get the hash table to actually give me 
back all the my inserts instead of the last insert multiplied by the number
of inserts?

TIA,
Adrian




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]