Re: Glib problem: trying to use gpointer pointing to a structurein a GList. Getting segfault

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

 



Hi, you're not allocating a record anywhere, you've just declared a pointer to one and not initialised it. Also, g_strdup() will save you a little code.

John


Lucas Brasilino wrote:
#include <stdio.h>
#include <string.h>
#include <glib.h>

int main(int argc, char **argv)
{

        GList *dlist = NULL, *list = NULL;
        guint length,i;
        struct {
                guint index;
                gchar *data;
        } *record;

I'd do


	typedef struct _Record {
		int index;
		char *data;
	} Record;

Record *rp;

        record->data = g_malloc(strlen("Lucas")+1);Lucas"
        g_strlcpy(record->data,"Lucas",strlen("Lucas")+1);
        dlist = g_list_append(dlist, record);

here do:


	rp = g_new( Record, 1 );
	rp->index = 0;
	rp->date = g_strdup( "Lucas" );
	dlist = g_list_append( dlist, rp );
	

record->data = g_malloc(strlen("Brasilino")+1); g_strlcpy(record->data,"Brasilino", strlen("Brasilino")+1); dlist = g_list_append(dlist, record);

same here




length = g_list_length(dlist);


g_printf("%d \n",length);

        record = NULL;g_list_first(dlist)
        list = g_list_first(dlist);
        while(list)
        {
                record = list->data;
                g_print("%s\n",record->data);
                list = list->next;

And change these to:


		rp = (Record *) list->data;
		printf( "index = %d, name = \"%s\"\n", rp->index, rp->data );
		list = list->next;

You could change the loop to:

	for( list = g_list_first( dlist ); list; list = list->next ) {
		rp = (Record *) list->data;
		printf( "index = %d, name = \"%s\"\n", rp->index, rp->data );
	}

which is slightly easier to read

    }
}

================




[Index of Archives]     [Touch Screen Library]     [GIMP Users]     [Gnome]     [KDE]     [Yosemite News]     [Steve's Art]

  Powered by Linux