October 9th, 2003, 08:29 PM
-
weird problem with qsort and structs
im having a weird problem with qsort:
my struct:
PHP Code:
struct mynode{
struct mynode *next;
char *path;
char *key;
int size;
};
typedef struct mynode mynode;
compare function:
PHP Code:
int compare(const void *pa,const void *pb){
const mynode *a=(mynode*)pa;
const mynode *b=(mynode*)pb;
return strcmp((char*)a->key,(char *)b->key);
}
i call qsort this way:
PHP Code:
aux=root;
mynode *no_ord[root->size];
for(i=0;i<root->size;++i){
no_ord[i]=aux;
aux=aux->next;
}
/* root is the head of a linked list (mynode) working nice (about 6000 nodes)*/
qsort(no_ord,root->size,sizeof (mynode*),compare);
it do it nice but if i check no_ord to see if everithing is in order, it seems to be sorting just in some places.
PHP Code:
for(i=0;i<root->size;++i)
printf("no_ord[%d]=%s\n",i,no_ord[i]->key);
a part of the output of that is this:
PHP Code:
no_ord[5597]=agrep
no_ord[5598]=dbiproxy
no_ord[5599]=dbish
no_ord[5600]=buildcast
no_ord[5601]=cast
no_ord[5602]=glimpse
as you can see 5600 isnt right! qsort is just moving things but it doesnt put them in order (no_ord is different before qsort)
what im doing wrong??? i want to use "key" as the reference.
Last edited by ToKu-John; October 9th, 2003 at 08:31 PM.
October 9th, 2003, 09:49 PM
-
Don't you need a swap routine somewhere? I don't think that qsort knows how to swap your structs.
October 9th, 2003, 11:05 PM
-
i got it!
the problem was with the compare function, i dont know why it worked before, but after a few tries it started to spit me with "seg faults". this is how it look now:
PHP Code:
int compare(const void *a,const void *b){
return strcmp((*(mynode**)a)->key,(*(mynode**)b)->key);
}
nice and clean :D