Re: C question



Thames wrote:
> ...
> 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....

You're probably recycling the variable you're passing as temp to your
add_item function. You have to be real careful when playing with
pointers because you WILL shoot yourself in the foot.

A more correct thing to do would be to malloc space to store the string
in your item_pointer variable (You can use strlen(text) + 1 to get
enough space to store the text plus the null that follows a string) and
then strcpy the string into the new storage. If you do that, it's also
good form to free all the junk you allocated before you exit the
program. Oh, and don't use global variables. Global variables cause
cancer.

You will want to put a lot of study into the behavior of pointers in
various contexts. Until you fully understand the tao of pointers, you
will never be a true C master.

--
Bruce Ide                                           
bruce.ide@echostar.com
"C has all the power of assembly language combined with all the ease of
programming of assembly language."




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