Re: C question



I guess the problem is about memory usage.
You didn't malloc some space for the text.
What you should do is :

void some_function (...)
{
    item temp;

    temp.text = g_malloc( SIZE );
   strcpy( temp.text, ".........." );
   add_item(temp);
}

You cannot simply set a string to a pointer without allocating memory space
for that string.

Jiang

Thames wrote:

> Hi...
> I have a question about general C.
> Cut down to the bone, the problem is:
> I have defined af structure:
>
> typedef struct {
>    gchar *text;
> } item;
>
> In a function (a callback function) I define a variable of item and
> assigns a value to the member variable text:
>
> void some_function (...) {
>    item temp;
>
>    temp.text = "Some text that the user defines and changes from time to
> time";
>    add_item(temp);
> }
>
> The add_item function is declared in the same file, and in the same file
> a global variable is defined, like this:
>
> GList *items;
>
> void add_item (item temp) {
>    item *item_pointer;
>    gint i;
>    gchar *temp_text;
>
>    item_pointer = (item*)g_malloc(sizeof(item));
>    item_pointer->text = temp.text;
>
>    items = g_list_append(items, item_pointer);
>
>    for(i=0; i <= g_list_length(items) - 1; i++) {
>      item_pointer = g_list_nth_data(items, i);
>      temp_text = item_pointer->temp;
>      g_print(temp_text);
>      g_print("\n");
>    }
> }
>
> It is clear that I want to make a list that grows when i append items to
> the list, and then I want, in the for loop, to show the text that is
> stored in all the items in the list.
> When I first time run the the hole thing, the right text is printed out,
> but when I run the functions again with a different text, that text is
> shown two times. It is like the first text I assigned is somehow lost,
> and the *text pointer in the two elements in the items list is pointing
> to the same text.
> What is wrong with the code?? And how can I do i different so it works?
>
> Thanks...
> Thames
>
> _______________________________________________
> gtk-list mailing list
> gtk-list@gnome.org
> http://mail.gnome.org/mailman/listinfo/gtk-list





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