gpt4 book ai didi

c - 为什么回调函数中的值不同 - 不好?

转载 作者:行者123 更新时间:2023-11-30 15:10:02 29 4
gpt4 key购买 nike

非常简单的应用程序 - 您可以复制 - 粘贴 - 运行。主要只是“创建”应用程序。 - 这不是问题(可能)

#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;
}

当我运行应用程序时 - 它以预期的方式打印函数“test_fce”的 3 次输出(一些地址和正确的变量值)。

但是当我单击按钮时,所有打印的地址都是正确的(与 test_fce 中相同)但是“a”的值不好(似乎总是0),“p”的值不好(似乎总是 000000...)所以我尝试访问“*p”程序的线路失败了。

代码有什么问题?

编辑:修复它的“最佳”方法是什么?

最佳答案

在函数返回后,您正在使用函数 activate 中的自动存储类变量,从而导致未定义的行为。

关于c - 为什么回调函数中的值不同 - 不好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36422147/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com