Passing a pointer to a function but the pointer remains unchanged

0

I have created the following two files to illustrate what my problem is.

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

I want to modify the original file pointer in the check_file function, but I find that I cannot do that for some reason.

Here is what I get when I run this program:

-1137322208
0
0
-559038737
0

It seems that check_file function gets only the copy of my_struct.file, but since it accepts a pointer, shouldn't the value of my_struct.file, which is an address, be assigned to GFile *file, which is supposed to be set to an address, as if I wrote GFile *file = my_struct.file;? Then file and mystruct.file would point to the same location in memory.

c
pointers
gtk
gtk3
asked on Stack Overflow Sep 7, 2018 by Hanlon • edited Sep 7, 2018 by Hanlon

1 Answer

1

What about this: if you want to change the value pointed by file, you must pass a pointer on the pointer...

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

And use it this way :

check_file(&my_struct.file);
answered on Stack Overflow Sep 7, 2018 by Mathieu

User contributions licensed under CC BY-SA 3.0