c - 将指针传递给函数但指针保持不变

标签 c pointers gtk gtk3

我创建了以下两个文件来说明我的问题所在。

main.c

#include <gtk/gtk.h>
#include "app_struct.h"

static void activation(GtkApplication *app, gpointer user_data);
static void check_file(GFile *file);

int main(int argc, char **argv)
{
        int status;

        GtkApplication *test = gtk_application_new("idk.for.now.test", G_APPLICATION_FLAGS_NONE);
        g_signal_connect(test, "activate", G_CALLBACK(activation), NULL);
        status = g_application_run(G_APPLICATION(test), argc, argv);
        g_object_unref(test);
        return status;
}

static void activation(GtkApplication *app, gpointer user_data)
{
        // create app my_struct
        struct app_struct my_struct;

        g_print("%d\n", my_struct.file);
        // set no file
        my_struct.file = NULL;
        g_print("%d\n", my_struct.file);
        check_file(my_struct.file);
        g_print("%d\n", my_struct.file);

        // add application to my_struct
        my_struct.app = app;
}

static void check_file(GFile *file)
{
        g_print("%d\n", file);
        file = (GFile *) 0xdeadbeef;
        g_print("%d\n", file);
}

app_struct.h

#ifndef APP_STRUCT_H
#define APP_STRUCT_H
struct app_struct
{
        GtkApplication *app; 
        GFile *file;
};
#endif

我想修改check_file中的原始文件指针函数,但我发现由于某种原因我无法做到这一点。

这是我运行该程序时得到的结果:

-1137322208
0
0
-559038737
0

看来check_file函数仅获取 my_struct.file 的副本,但由于它接受指针,因此不应该 my_struct.file 的值,这是一个地址,被分配给 GFile *file ,应该设置为一个地址,就像我写的 GFile *file = my_struct.file; ?然后filemystruct.file将指向内存中的同一位置。

最佳答案

这样怎么样:如果你想改变文件指向的值,你必须在指针上传递一个指针...

static void check_file(GFile **file)
{
        g_print("%p\n", *file);
        *file = (GFile *) 0xdeadbeef;
        g_print("%p\n", *file);
}

并以这种方式使用它:

check_file(&my_struct.file);

关于c - 将指针传递给函数但指针保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52226483/

相关文章:

java - 如何在 Java Gnome/GTK 程序中使用 Glade UI(.glade 文件)?

gtk - 在客户端浏览器中运行 GTK+ 应用程序

c - 什么样的非致命代码通常会触发防病毒软件? (误报)

C 宏 : #if check for equality

c++ - 如何初始化和定义指向二维数组的指针?

c++ - 使用 pop_back 时防止指针失效

c - 共享库 (PIC) 返回指向调用者结果的指针 SEGFAULT

const unsigned char[][] 的 C 数组

c - 带有指向数组指针的指针算术

json - 使用 JSON 序列化 Gtk TreeStore/ListStore