qsort()

Adam S. Denton asd at cbnewsj.att.com
Tue Apr 23 03:49:58 AEST 1991


In article <1991Apr22.002627.14535 at engin.umich.edu> garath at irie.ais.org (Belgarath) writes:
>qsort((char *) info, 49, sizeof(the_srtuct), compare);
>
>int compare(ptr1, ptr2) 
>struct the_struct *ptr1;
>struct the_struct *ptr2;
>{
>	return (strcmp(ptr1->name, ptr2->name));
>}

Not quite.  This should really be
    int compare(ptr1,ptr2)
         char *ptr1, *ptr2;
    {
         return strcmp( ((struct the_struct *)ptr1)->name,
                        ((struct the_struct *)ptr2)->name );
    }
and in an ANSI environment, "void *" should be used instead of "char *".

qsort() passes generic pointers to compare(), not struct pointers.
There is no guarantee the two pointer types are interchangeable.

Adam Denton
asd at mtqua.att.com



More information about the Comp.lang.c mailing list