非常简单的应用程序 - 您可以复制 - 粘贴 - 运行。 主要是“创建”应用程序。 - 这不是问题(可能)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <gtk\gtk.h>
typedef struct{
int a;
int *p;
}struct_int;
static void test_fce(gpointer data){
struct_int *local = (struct_int *)data;
printf("\n");
printf("local %p\n", local);
printf("local a %i\n", local->a);
printf("local &a %p\n", &(local->a));
(local->a)++;
printf("local p %p\n", local->p );
printf("local &p %p\n", &(local->p));
printf("local *p %i\n", *(local->p));
(*(local->p))++;
}
static void write_value(GtkButton *button,
gpointer data)
{
struct_int *local = (struct_int *)data;
printf("\n");
printf("local %p\n",local);
printf("local a %i\n", local->a);
printf("local &a %p\n", &(local->a));
printf("local p %p\n", local->p );
printf("local &p %p\n", &(local->p));
printf("local *p %i\n", *(local->p));
}
static void activate (GtkApplication* app,
gpointer user_data)
{
int i = 7;
GtkWidget *main_window, *button;
struct_int test_struct;
main_window = gtk_application_window_new (app);
button = gtk_button_new_with_label ("Start");
gtk_container_add (GTK_CONTAINER (main_window), button);
gtk_widget_show_all (main_window);
test_struct.a = 5;
test_struct.p = &i;
printf("i %i\n",i);
printf("&i %p\n",&i);
printf("test_struct_p& %p\n", &test_struct);
printf("test_struct_p a %i\n", test_struct.a);
printf("test_struct_p &a %p\n", &(test_struct.a));
printf("test_struct_p p %p\n", test_struct.p);
printf("test_struct_p &p %p\n", &(test_struct.p));
printf("test_struct_p *p %i\n", *(test_struct.p));
test_fce((gpointer) &test_struct);
test_fce((gpointer) &test_struct);
g_signal_connect (G_OBJECT(button), "clicked", G_CALLBACK (write_value), (gpointer) &test_struct);
test_fce((gpointer) &test_struct);
}
int main (int argc,
char **argv)
{
GtkApplication *app;
int status;
gtk_init(&argc, &argv);
app = gtk_application_new ("a.b.my_app", G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
status = g_application_run (G_APPLICATION (app), argc, argv);
g_object_unref (app);
return status;
}
当我运行应用程序时 - 它以预期的方式打印3次函数“test_fce”的输出(某些地址和变量的正确值)。
但是当我点击Button时,所有打印的地址都是corect(与test_fce相同)但是 “a”的值很差(似乎总是0), “p”的值很差(似乎总是000000 ...) 所以在我试图访问“* p”程序的时候会掉线。
代码有什么问题?
编辑:什么是“最好的”解决方法?
答案 0 :(得分:1)
在函数返回后,您正在使用函数activate
中的自动存储类变量,从而导致未定义的行为。