c-从不同的函数插入GLib树

  • 本文关键字:插入 GLib 函数 c glib
  • 更新时间 :
  • 英文 :


我不确定我是否遗漏了什么,这可能会让这个问题变得非常愚蠢。但我不明白,在尝试了几乎所有可能的方法后,它为什么会失败。

所以,非常简单,我有这个GLib树,我想在其他函数中插入一些东西。为什么下面的选项都不起作用?老实说,我更能理解第一次失败而不是第二次失败。

int compare_ints(gconstpointer gpa, gconstpointer gpb){
int a = *((int*) gpa);
int b = *((int*) gpb);
return (a-b);
}
void test1(GTree* tree){
int code = 1234;
gpointer gcp = &code;
g_tree_insert(tree, gcp, gcp);
printf("%dn", (g_tree_lookup(tree, gcp) == NULL)); // Outputs 0 (obviously)
}
void test2(GTree** tree){
int code = 1234;
gpointer gcp = &code;
g_tree_insert(*tree, gcp, gcp);
printf("%dn", (g_tree_lookup(*tree, gcp) == NULL)); // Outputs 0 (obviously)
}
int main(int argc, char** argv){
GTree* tree = g_tree_new(compare_ints);
int code = 1234;
gpointer gcp = &code;
test1(tree);
printf("%dn", (g_tree_lookup(tree, gcp) == NULL)); // Outputs 1 (Why?)
test2(&tree);
printf("%dn", (g_tree_lookup(tree, gcp) == NULL)); // Outputs 1 (Why?)
return 0;
}

很抱歉,如果这是一个愚蠢的问题,请提供任何帮助:(

编辑:删除了vim线符号

正如@UnholySheep在主线程的评论中提到的那样,执行以下操作将起作用:

void test1(GTree* tree, int* code){
g_tree_insert(tree, code, code);
printf("%dn", (g_tree_lookup(tree, code) == NULL));
}
void test2(GTree** tree, int* code){
g_tree_insert(*tree, code, code);
printf("%dn", (g_tree_lookup(*tree, code) == NULL));
}
int main(int argc, char** argv){
Catalog* c = init_catalog(26, 1, compare_ints);
int* code = malloc(sizeof(int));
*code = 1234;
GTree* tree = g_tree_new(compare_ints);
test1(tree, code);
printf("%dn", (g_tree_lookup(tree, code) == NULL));
test2(&tree, code);
printf("%dn", (g_tree_lookup(tree, code) == NULL));
destroy_catalog(c);
free(code);
return 0;
}

这之所以有效,是因为代码只有在您释放它时才会消失!

在函数末尾的初始情况下,int将停止存在,这将证明行为的合理性。如果你有兴趣阅读更多关于它的内容,请查看邪恶羊在主线程评论中提到的链接!

最新更新