Re: Problem with linked lists and CLists



On 2 Aug 2002, Gustavo Giráldez wrote:

> Hi,
>
> On Thu, 2002-07-25 at 23:53, Szymon B±kowski wrote:
> > Hello everyone :)
> > I`m jus started writting in GTK+ 1.2 and I stuck in two points:
> > first I was trying tu put something from two dimensional array to CList but
> > I get again and again error but not during compilation but during program
> > run.
>
> What error are you getting at runtime?  The code looks ok (though I
> didn't actually try it).

It certainly does NOT!

(or at least, the snippet below with the double linked list contains clear
signs of standard C misunderstandings)

>
> [snip]
>
> > My second question is about double linked list in gtk. I created something
> > like this:
> >
> >
> > char numerr[]={"123"};
> > struct komp
> > {
> >     char *numer;
> >     char *ip;
> >     char *stan;
> > };
> > struct komp *elementy;
> > elementy=malloc(sizeof(struct komp));

This allocates memory for a komp structure (12 bytes on a standard 32-bit
platform, perhaps padded to 16 bytes).

It does not set the three pointers inside the structure to any value.
Neither does it allocate any memory for these pointers to point to.

> > strcpy(elementy->numer,numerr);

strcpy() doesn't allocate any memory.  It blindly assumes that the first
parameter points to a chunk of memory that is big enough to hold the
zero-terminated string that the second parameter points to (including the
zero at the end).  In this case, four bytes.

Unfortunately, elementy->numer has NOT been set to any valid value.

This is not GTK+ or Gnome, just standard (very simple!) C.

You can allocate the buffer to hold the copy manually or you can use the
strdup() function:

  elementy->numer = strdup(numerr);

Be forewarned, though, that even though almost all platforms support that
function, it is NOT part of Ansi C (or did they put it into C99?).

GTK+ has an equivalent that is guaranteed to work whereever GTK+ is
installed:

  elementy->numer = g_strdup(numerr);

So that's probably what the original poster wants to use.

> > list_ko=g_list_append(list_ko,(gpointer)elementy);
> > printf("%s\n",(char*)list_ko->elementy->numer);
> >
> > and maybe stupid question I don`t knw how to get tu the "numer" element of
> > this
>
> A doubly-linked list is composed of nodes which have the following
> structure:
>
> struct GList
> {
>   gpointer data;
>   GList *next;
>   GList *prev;
> };
>
> So, to access your data you need to cast the "data" field or by using
> the g_list_nth_data function.  Read the reference manual for more
> information.

I suggest the original poster also consult a C book :)

-Peter




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