GLib tree insertion always inserts in the same node

杀马特。学长 韩版系。学妹 提交于 2019-12-25 00:55:12

问题


I have this very simple piece of code

GTree* teste = g_tree_new(cmp);

  for(int i = 0; i < 10; i++){
    g_tree_insert(teste, &i, &i);
    printf("%d", g_tree_nnodes(teste));
  }

The "cmp" function is

int cmp(const void *a, const void* b){
  int* ia = (int*)a;
  int* ib = (int*)b;
  return (*ia - *ib);
}

I don't understand why, but the number of nodes is always one. It seems the compare function is not being used properly, and it always asserts to 0.


回答1:


The documentation on this functions says:

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 the GTree, the old value is freed using that function. If you supplied a key_destroy_func when creating the GTree, the passed key is freed using that function.

So duplicate keys are not allowed. The value will just being overwritten.

You need to allocate both key and a value separately and use g_tree_new_full to create a tree, supplying destruction functions.

So your code should look like this:

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

int cmp(const void *a, const void *b, void *data)
{
  int *ia = (int *) a;
  int *ib = (int *) b;
  return (*ia - *ib);
}

int main(void)
{
    GTree* teste = g_tree_new_full(&cmp, NULL, &free, NULL);

    for(int i = 0; i < 10; i++){
        int *kv = malloc(sizeof i);
        *kv = i;
        g_tree_insert(teste, kv, kv);
        printf("%d", g_tree_nnodes(teste));
    }

    putchar('\n');
    g_tree_unref(teste);
}


来源:https://stackoverflow.com/questions/55424486/glib-tree-insertion-always-inserts-in-the-same-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!