Charles Sullivan wrote on 20/09/05 :
> Here's an example which illustrates the way I've been using
> qsort:
> -------------------------------------
> #include <stdio.h>
> #include <stdlib.h>
>
> int val[] = { 3, 2, 1, 4, 5 };
>
> int cmp_fcn ( int *one, int *two )
Wrong prototype.
> {
> return (*one < *two) ? -1 :
> (*one > *two) ? 1 : 0;
Complicated. A simple difference is enough. The 3 domains are <0, 0, >0
> }
>
> int main ( void )
> {
> int (*fcmp)() = &cmp_fcn;
Useless pointer to function masking the parameters error.
> qsort((void *)val, 5, sizeof(int), fcmp);
USeless cast. Now, I have a 18 values array of doubles. What do I do ?
> printf("%d %d %d %d %d\n",
> val[0], val[1], val[2], val[3], val[4]);
Now, I have a 18 values array of ints. What do I do ?
> return 0;
> }
> -----------------------------------
stay stright, simple and conforming:
#include <stdio.h>
#include <stdlib.h>
#define NELEM(a) (sizeof (a) / sizeof *(a))
static int cmp_fcn (void const *one, void const *two)
{
int const *p_one = one;
int const *p_two = two;
return *p_one - *p_two;
}
static void print (int const *a, size_t n)
{
size_t i;
for (i = 0; i < n; i++)
{
printf ("%d ", a[i]);
}
printf ("\n");
}
int main (void)
{
int val[] =
{3, 2, 5, 1, 4};
print (val, NELEM (val));
qsort (val, NELEM (val), sizeof *val, cmp_fcn);
print (val, NELEM (val));
return 0;
}
--
Emmanuel
The C-FAQ:
http://www.eskimo.com/~scs/C-faq/faq.html
The C-library:
http://www.dinkumware.com/refxc.html
"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++