Re: help with linked lists
- From: John Cupitt ng-london org uk
- To: p dirac org
- Cc: gtk-list gnome org
- Subject: Re: help with linked lists
- Date: Mon, 25 Feb 2002 18:08:00 -0000
Peter Jay Salzman wrote:
> typedef struct {
> SDL_Surface *img;
> int magnitude;
> SDL_Rect rect;
> } ChargeStruct;
>
> and i have a double linked list of them:
>
> GList *ChargeList = NULL;
> ChargeStruct puck;
> ...
> ChargeList = g_list_append (ChargeList, &puck);
Hi Peter,
Is ChargeStruct a local? You probably want to allocate space for a
struct of the heap, and then add a pointer to that area to your list.
ChargeStruct *puck = g_new (ChargeStruct);
ChargeList = g_list_append (ChargeList, puck);
(also, _prepend() is much faster if you don't care about having the
order reversed)
(also GList keeps forwards and back pointers ... if you just want a
one-way list, you can use GSList (singly-linked list) and save a little
space)
(also the usual convention is to use MixedCaps for type names, and
underscore_names for variables ... so I'd call ChargeList charge_list)
Of course, you'll need something to g_free() all these pucks when you're
done with them.
> ChargeStruct *ChargeClicked(GList *ChgList, SDL_Event event)
> {
> GList *ptr;
> int x, y;
>
> while (ptr != NULL) {
> ptr = g_list_next(ChgList);
> x = ptr->data->rect.x;
> y = ptr->data->rect.y;
> if (event.button.x > x - 10 && event.button.x < x + 10) {
> printf("click\n");
> }
> }
> return(ptr->data);
> }
You need to init ptr to the start of your list, and you need to cast ptr
to ChargeStruct* (the compiler does not know what sort of thing you have
in your list ... it just sees a dumb pointer).
the usual g_idiom for iterating over lists is
GList *i;
for( i = ChargeList; i; i = i->next ) {
ChargeStruct *puck = (ChargeStruct *) i->data;
if( puck->rect.x ... etc.
}
John
==========================================================
Aelbert Cuyp 13 February - 12 May 2002
For information and tickets:
http://www.nationalgallery.org.uk
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]