Re: [gtk-list] GHashTable questions



//(I think I'm missing something very basic here)

I think I agree, as far as I understand your problem...

//Why does g_hash_table_new have to be called from 
//main (along with g_hash_table_insert) if one needs
//to look up values in various other functions?
//
//If I do the insertion in functions other then main, 
//and do lookups in other functions, I get (nil).
//This happens even though the hash table and the 
//other variables are globally defined..

Are you talking C? (That (nil) notation is Lisp, isn't it?)

In C you would do:

my_hash = g_hash_table_new( my_hash_func, my_equal_func );

This creates a new hash table, pointed to by my_hash. my_hash_func computes 
hash values (integers) from the keys that you intend to use, and my_equal_func 
checks if two of your keys are equal. Implementations of these for strings are 
present in glib.

And then, anywhere else where you can get at the value of my_hash:

g_hash_table_insert( my_hash, my_key, my_value );

This inserts the value under the key in the hashtable.

Finally followed by:

some_value = g_hash_table_lookup( my_hash, my_key );

Which would return the value associated with the key, if any such is present, 
or NULL otherwise.


But perhaps your problem is that you use local variables as keys and values? 
The hash table does not copy your keys and values, and I don't think it 
attempts to call free on them either. So if you insert like this:

void my_func( )
{
  MyStruct foo;

  foo.bar = 12;

  g_hash_table_insert( my_hash, "my-key", &foo );
}

After my_func returns, g_hash_table_lookup( my_hash, "my-key" ) will return a 
pointer to that local variable that does not exist anymore...

//Thanks,
//Sam

Hope that helps,

Johannes.
--
MtG: "A boosterpack a day keeps the doctor away."

How do I connect to that real-life thing I keep hearing about?




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