Re: Combo Box question



Note: this is my first application using GTK :-). I would like create
automatically a COMBO box with numeric values assigned to it as following
example:

GList *items = NULL;

Remember that the GList stores only pointers or integers, and if you append
something to a g_list, you de facto only append the pointer to a memory
fragment, and if you change that memory later by directly accessing a
pointer you will change also the g_list element.

GtkWidget *combo;
gchar *buffer[20];

You have created an array of pointers to char. Is this exactly what you had
in mind? I have the impression that you had something else in mind, which
also was wrong :-) To be more specific, I think you wanted to create a string
buffer common for all the five items of your glist, which will not work,
because g_list_append does not copy the contents of your buffer, but only
the pointer to it. That means, that if you add *the same* pointer to the
GList several times, and each time something different is in the memory
chunk the pointer is pointing to, all the elements in the GList will point
to the same piece of memory after you are finished, and you will end up
with a list containing five identical elements.

for (i=0;i<5;i++)
{
sprintf (buffer, "%d", i);

// probably something is missing here ?

Well, buffer is of type gchar**. You are trying to print %d not onto a
string, but onto a pointer-to-a-pointer-to-a-char, that is, on a
pointer-to-a-string. 

There are two easy solutions I see.

1). You keep the slightly changed definition of buffer:
        gchar *buffer[5] ;

        ...

        for(i=0 ; i<5 ; i++) {
                buffer[i]=malloc(2) ;
                sprintf(buffer[i], "%d", i) ;
                items = g_list_append(items, buffer[i]) ;
        }

Note that you may not free the malloc'ed buffers before you are done with
your Combo box! 

2). You take a pre-filled array.
        
        gchar buffer[5][2] = { "0", "1", "2", "3", "4" } ;

        ...

        for(i=0 ; i<5 ; i++) items = g_list_append(items, buffer[i]) ;

This is the less elastic, but an easier way.

Cheers,
j.

----)-\//-///-----------------------------------January-Weiner-3-------
Zły - być może, dobry - a czemu? Nie tak wiele pychy we mnie!            
Dajcie żyć po swojemu, grzesznemu, to i świętym żyć będzie przyjemniej...





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