Re: Pass by reference...(easy question)



On Thu, 3 May 2007, beginner.c wrote:

I know how to pass by reference in C normally. But how do I pass by ref a
GTK Widget to a function?

The same way, by giving the address of the object.  However, with 
a GtkWidget what you have in hand is already a pointer so in most 
cases it suffices to pass that pointer.

Totally useless but hopefully illustrative code follows:

#include <gtk/gtk.h>

void f1 (GtkWidget *w)
{
    gtk_widget_show(w);
    gtk_widget_destroy(w);
}

void f2 (GtkWidget **pw)
{
    gtk_widget_show(*pw);
    gtk_widget_destroy(*pw);
    *pw = NULL;
}

int main (int argc, char **argv)
{
    GtkWidget *w;

    gtk_init(&argc, &argv);

    w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    printf("created new GtkWidget at %p\n", (void *) w);

    f1(w);
    /* bzzt, invalid pointer below; it has been freed */
    printf("After f1(), w = %p\n", (void *) w);

    w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    printf("created new GtkWidget at %p\n", (void *) w);

    f2(&w);
    printf("After f2(), w = %p\n", (void *) w);

    return 0;
}

Here, the above prints:

created new GtkWidget at 0x8079000
After f1(), w = 0x8079000
created new GtkWidget at 0x80790a8
After f2(), w = (nil)

Allin Cottrell



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]