Karol Szustakowski Karol Szustakowski - 3 months ago 10
C++ Question

Use a variable from pointer that is pointed by a struct which (that structs') pointer is sent to a function that needs to use it

Welp, thats a kind of a pointerception.

So.

Im using gtk+

In gtk I define buttons like this:


GtkWidget *button1, *button2;


so I need a function do do something with this. So I make a struct that will hold a pointer to it

Here it is:


typedef struct userdata{
GtkWidget *button1, *button2;
}userdata;


I point pointers from struct to pointers from main:

userdata data;
data.button1 = button1;
data.button2 = button2;


Then I use this struct with gtk event:

g_signal_connect(G_OBJECT(window), "configure-event", G_CALLBACK(resetbuttonsize), &data);


And here comes the problem. I want to do something with these variables I just sent to function, for example resize them so I do something like this:

void resetbuttonsize(GtkWindow *window, GdkEvent *event, gpointer data){
GtkWidget *button1 = data->button;
}


So I could then do something like:

gtk_widget_set_size_request(button1, 40, 40);


Sadly, I can not to this (GtkWidget *button1 = data->button;) because I get the following compiler error:


/media/dysk250/pmanager/testfile/main.cpp|59|error: ‘gpointer {aka void*}’ is not a pointer-to-object type|


Can someone tell me what Im doing wrong?
Im newbie with pointers, maybe I could resolve single pointer pointer, but this one is just too much for my brain to understand what is happening and why code I use is wrong.

Answer

You need to cast the void* variable into a suitable pointer that can be dereferenced:

GtkWidget *button1 = static_cast<userdata*>(data)->button;