Re: why???

On Thu, Sep 07, 2006 at 07:35:20PM -0700, dagang001 wrote:

#include <glib.h>

typedef struct {
    gchar * name;
    gint shoe_size;
    gint age;
} Person;

int main(int argc, char** argv) {
    Person *fred = g_new(Person, 1);
    GList *list = NULL;

    gint num,i;
    gchar *ming[]={"aaa","bbb","ccc","ddd"};

    for ( i=0 ;i<4 ;i++)
        fred->name = ming[i];
        fred->shoe_size = i+10;
        list = g_list_append(list, fred);

    num=g_list_length (list);

    for (i=0 ;i<num;i++)
        g_print("%d '%s' %d  %d \n", i,
                ((Person *)g_list_nth (list,i)->data)->name,
                ((Person *)g_list_nth (list,i)->data)->shoe_size,
                ((Person *)g_list_nth (list,i)->data)->age);

    g_print("long%d \n\n", num);
    g_list_free (list);

    return 0;


0  'ddd' 13 63
1  'ddd' 13 63
2  'ddd' 13 63
3  'ddd' 13 63

GList (like many other GLib data structures) holds

fred points all the time to the same piece of memory (the
same instance of Person).  So you add four identical
pointers to the list.  During the additions you change the
fields inside fred, but it's still one instance.  At the end
you print four times the contents of fred.

To add four different instances of Person, create four
different instances of Person and add them.


Anonyms eat their boogers.

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