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

时间:2018-09-07 16:31:02

标签: 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指向内存中的相同位置。

1 个答案:

答案 0 :(得分:1)

这怎么办:如果要更改文件所指向的值,则必须在该指针上传递一个指针...

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

并以这种方式使用它:

check_file(&my_struct.file);