Hello,
I'm trying to wrap my head around using
glib for its list and sorting routines, in the hope that I'd be doing myself a favour in using robust code ...
I discovered that I have 2 big problems here, one of which there may be no solution to.
What I need to do is create
n nodes, insert them into the list, calculate a number then sort them based on the number.
I recognised that I would need a
struct for the node data as
GSList only has a single pointer and single variable.
GSList
Problem is, each
struct would need to be named, so I expect that I would need to have anticipated every name ... which means I don't really think I'm approaching the problem correctly ... I suspect there may be no direct remedy for this.
Second, I get an error at compile-time - it complains that it expected
GCompareFunc but got something like
GInt.
I do apologise for not having the exact error - I'll paste it when I get to work tomorrow (my home machine doesn't like to locate any libs at all so I can't reproduce it... :/ )
Suffice to say, I don't get what it wants in terms of being a
GCompareFunc.
Details:
I have been using
this IBM tutorial on data management with Glib.
Eventually, I want to be able to read a series of numbers from a file (probably a .csv) then add that number of new items to my list.
The random number simply pretends to be the number from a file.
The following code is, clearly, broken... but maybe it'll help explain what I'm trying to achieve.
I've attempted writing my own lists, I was using a doubly linked list of Struct with next* and prev* pointers in there but I couldn't get it to work - I know, shame on me...
Code:
//lists.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>
#include <glib.h>
typedef struct {
int id;
int iq;
} Person;
gint my_comparator(gconstpointer item1, gconstpointer item2) {
return item1 - item2;
}
int main(int argc, char** argv) {
GSList* list = NULL;
int i;
srand(time(NULL)); //random number takes the place of file input for now
for(i = (rand() % 100); i > 0; i--){
Person* !problem! = g_new(Person, 1); // allocate memory for one Person struct
!problem!->id = i; // !problem! = here's the problem
!problem!->iq = (rand() % 200);
list = g_slist_prepend(list, !problem!); //prepend for speed
}
list = g_slist_sort(list, (GCompareFunc)my_comparator); //something really wrong here
return 0;
}