Re: why???



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;
        fred->age=60+i;
        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);
    g_free(fred);

    return 0;
}


result:

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

help me !!



1) because g_list_append() does only copy the _pointer_ from fred to the
list... all 4 list elements _point_ to the same fred in the end...

2) try doing this with ansi-C-functions-only instead ...it will be
better for your development of skill in the long run to avoid someones
proprietary (and pretty redundant) framework... later you will write
your own mapping stuff and laugh about this...

Dirk



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