Reputation: 6892
The C code
#include <glib.h>
//...
GHashTable *hash = g_hash_table_new(NULL, NULL);
GString val;
g_hash_table_insert(hash, (int*)5, g_string_new("Bar"));
val = g_hash_table_lookup(hash, (int*)5); // line 10
printf("Foo ~ %s\n", val->str); // line 16
if (NULL == val) // line 18
printf("Eet ees null!\n");
Which produced:
ctest.c:10: error: incompatible types in assignment
ctest.c:16: error: invalid type argument of '->' (have 'GString')
ctest.c:18: error: invalid operands to binary == (have 'void *' and 'GString')
What am I doing wrong? :(
EDIT: Some might be confused and ask ask themselves "Why didn't she use g_string_printf()
?"
Because I need to access gchar *str
, printing was just my way of "debugging" it.
EDIT: Added line 18, and commented the spazzing lines (yes, lots of whites-paces all over the place. I'm dreadful, I know).
Upvotes: 0
Views: 3612
Reputation: 145899
A GString structure is declared as:
struct GString {
gchar *str;
gsize len;
gsize allocated_len;
};
so to access the string just use the .
operator:
printf("%s\n", val.str)
Also passing (int*) 5
as an argument to your function is probably wrong. This converts the integer value 5
to a pointer. But what you want is a pointer to an int
where the int
value is 5.
To do this you can either use a compound literal: &(int) {5}
or use a pointer to an object of type int
:
int bla = 5; // and you pass &bla as the argument of your function
Upvotes: 1
Reputation: 182664
The function g_string_new
returns a GString *
. So that's what's getting stored in the hash. And the function g_hash_table_lookup
returns a void *
. You likely want something like this:
GString *val;
val = g_hash_table_lookup(hash, (int*)5);
printf("Foo ~ %s\n", val->str);
Upvotes: 2
Reputation: 16718
val->str
should be val.str
- it's not a pointer. This also means you can't do if (NULL == val)
.
Upvotes: 0