GTK signal in a for loop

Hi,

I have this code snippet, I want to send i as valued in for loop. But I always get 4 sent to g_signal_connect , what to do ?

#define RECENTS_COUNT 5
GtkWidget *recents_ptr[RECENTS_COUNT+1]; // sub-menu members
int main(int argc, char *argv[])
{
    [...]

gint i;
    for( i=0; i<RECENTS_COUNT; i++)
    {
        gchar stri[20];
        g_print("si is %d\n",i);
        g_sprintf(stri,"Stri i is %d\n",i);
        g_signal_connect(G_OBJECT(recents_ptr[i]),"activate"
                         ,G_CALLBACK(choice_clicked),stri); // why all i is 4 ?
    }
                     gtk_widget_show_all(window);
                     gtk_main();
                     return 0;
}

What ever sub-menu I click , I get:

Stri i is 4

What ever sub-menu I click , I get:

Stri i is 4

This is because you just update the content of the stri buffer, but your g_signal_connect() call does not copy the current value. Thus, you just get whichever was the last data you wrote in there. You must copy the string. Iā€™d recommend g_strdup_printf(), and to use g_signal_connect_data(G_OBJECT(recents_ptr[i]), "activate", G_CALLBACK(choice_clicked), stri, (GClosureNotify)g_free, 0)

1 Like

Thanks , your idea worked.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.