我创建了以下两个文件来说明我的问题所在。
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;
?然后file
和mystruct.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/