【问题标题】:Inserting into GLib Tree from different functions [duplicate]从不同的功能插入GLib树[重复]
【发布时间】:2020-03-01 18:52:01
【问题描述】:

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

所以,超级简单,我有这个 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("%d\n", (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("%d\n", (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("%d\n", (g_tree_lookup(tree, gcp) == NULL)); // Outputs 1 (Why?)
     test2(&tree);
     printf("%d\n", (g_tree_lookup(tree, gcp) == NULL)); // Outputs 1 (Why?)

     return 0;
 }

对不起,如果这是一个愚蠢的问题,任何帮助都非常感谢:)

编辑:删除 vim 行符号

【问题讨论】:

  • gpointer gcp = &code; 创建一个指向具有自动存储持续时间的值的指针。在函数退出后将该指针插入树中将该指针变为悬空指针
  • @UnholySheep 老实说我完全不明白。你的意思是我确实在改变树但是当我离开函数时我所做的改变被“改变”了?如果是这样,那么我该如何解决这个问题?因为我需要一个 gpointer,并且我需要在其他函数中将东西插入到树中:/
  • @UnholySheep 我查了一下,发现我不需要将 int 转换为 gpointer,我猜这个事实让我特别困惑。那么,改变它应该使程序工作吗? (只是问,因为我没有立即访问测试的地方并且可以回答)感谢您的帮助,一旦我设法测试出差异,我会将这篇文章标记为通过您的链接解决!
  • 您需要做的是分配键和值,使它们比函数调用更“活跃”。例如:通过使用malloc(但你需要确保它得到free'd)

标签: c glib


【解决方案1】:

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

void test1(GTree* tree, int* code){
    g_tree_insert(tree, code, code);
    printf("%d\n", (g_tree_lookup(tree, code) == NULL));
}

void test2(GTree** tree, int* code){
    g_tree_insert(*tree, code, code);
    printf("%d\n", (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("%d\n", (g_tree_lookup(tree, code) == NULL));
    test2(&tree, code);
    printf("%d\n", (g_tree_lookup(tree, code) == NULL));

    destroy_catalog(c);
    free(code);
    return 0;
}

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

在函数末尾的初始情况下,int 将停止存在,这将证明该行为是正确的。如果您有兴趣阅读更多相关信息,请查看 UnholySheep 在主线程的 cmets 中提到的链接!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 2016-01-20
    • 2022-12-22
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多