Re: How to use GList Double Link List



sumit kumar escribió:
*gint pos;
g_print("Enter Number1\n");
scanf("%d",&pos);
list = g_list_append(list, (gpointer)&pos);

g_print("Enter Number2\n");
scanf("%d",&pos);
list = g_list_append(list, (gpointer)&pos);

g_print("Enter Number3\n");
scanf("%d",&pos);
list = g_list_append(list, (gpointer)&pos);

g_print("Enter Number4\n");
scanf("%d",&pos);
list = g_list_append(list, (gpointer)&pos);
*
It prints only last element I appened 4 times... 44, 44 ,44 ,44 if I
appended 44 as last element.
Whats wrong with this code??

You're not alocating new space, the pos pointer is always pointing at the same cell, which by the way is never initialized. Also, when you use g_list_append you're passing a pointer to a pointer to an integer, and I don't think that's what you want. Do something like:

#include <stdio.h>
#include <glib.h>
#include <glib/gprintf.h>

int main (int argc, char **argv) {
        GList *tmp, *list = NULL;
        gint i, *element;
        
        /* Appends 4 integers into list */
        for (i=1; i<5; i++) {
                element = g_malloc (sizeof (gint));
                g_printf ("Enter Number %d: ", i);
                scanf ("%d", element);
                list = g_list_append (list, element);
        }
        
        /* Prints data in list */
        tmp = list;
        while (tmp) {
                element = tmp->data;
                g_printf ("%d\n", *element);
                tmp = g_list_next (tmp);
        }
        
        /* Frees the data in list */
        tmp = list;
        while (tmp) {
                g_free (tmp->data);
                tmp = g_list_next (tmp);
        }
        
        /* Frees the list structures */
        g_list_free (list);
        
        return 0;
}

GLib API Reference: http://developer.gnome.org/doc/API/2.0/glib/index.html
GLib Tutorial: http://gtk.org/tutorial/x2037.html



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