So I was trying to do a function that take a GTree*
a (each node of the Tree
is a struct User
) and an id
and it would search for that user
and increment a variable! (school project)
With some help from here, I managed to do but I didn't realize that it was not incrementing.
The structure is:
typedef struct user {
int id;
char username[256];
int post_count;
char short_bio[16384];
int reputation;
}*USER;
typedef struct TCD_community{
GTree* res;
GTree* quest;
GTree* users; /
}TCD_community;
typedef struct TCD_community * TAD_community;
TAD_community tq;
And function is (helped by a stackoverflow user):
void incrementaPost(GTree* a,int id){
gpointer ptr = g_tree_lookup ( a , &id);
struct user *u = (struct user *) ptr;
if(u){
u->post_count++;
}
}
I called that on main like:
incrementaPost( tq -> users, 703994);
Output:
Id 703994
Name N.Sinha
post_count 0
reputation 51
Expected:
Id 703994
Name N.Sinha
post_count 1
reputation 51
Please be aware that the GTree*
has to be properly constructed before you can do the search.
First construct the tree with the dedicated search function:
GTree *tree;
tree = g_tree_new(MySearchFunction);
Where
g_tree_new ()
GTree * g_tree_new (GCompareFunc key_compare_func);
Creates a new
GTree
.Parameters:
key_compare_func
the function used to order the nodes in the
GTree
. It should return values similar to the standardstrcmp()
function -0
if the two arguments are equal, a negative value if the first argument comes before the second, or a positive value if the first argument comes after the second.
Then your objects have to inserted using g_tree_insert ()
g_tree_insert ()
void g_tree_insert (GTree *tree, gpointer key, gpointer value);
Inserts a key/value pair into a
GTree
.If the given key already exists in the
GTree
its corresponding value is set to the new value. If you supplied a value_destroy_func when creating theGTree
, the old value is freed using that function. If you supplied a key_destroy_func when creating theGTree
, the passed key is freed using that function.Parameters
tree
- a
GTree
key
- the key to insert
value
- the value corresponding to the key
Only then, you can use g_tree_lookup
for the search.
Check this simple example - how to construct GTree*
, insert elements, do the search via g_tree_lookup
and traverse the tree via g_tree_traverse
.