This question already has answers here:
How to change value of variable passed as argument?
(4个答案)
change pointer passed by value
(6个答案)
Passing pointer to function value not changing [duplicate]
(4个答案)
Changing address contained by pointer using function
(5个答案)
Pointers as function arguments in C
(7个答案)
2年前关闭。
我创建了以下两个文件来说明我的问题是什么。
main.c
app_struct.h
我想在
这是我运行该程序时得到的:
似乎
并以这种方式使用它:
(4个答案)
change pointer passed by value
(6个答案)
Passing pointer to function value not changing [duplicate]
(4个答案)
Changing address contained by pointer using function
(5个答案)
Pointers as function arguments in C
(7个答案)
2年前关闭。
我创建了以下两个文件来说明我的问题是什么。
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);