Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

qsort structure array deletes everything

So I am having trouble using qsort to sort an array of structures.

I used this link as an example: http://support.microsoft.com/kb/73853

When I run the program it gives me blanks for the names that were originally in the structure and zeroes for all the values of gp.

typedef int (*compfn)(const void*, const void*);

struct record
{
    char player[20];
    int gp;
};
struct record entries[15];

int compare(struct record *, struct record *);


void show ()           
{
    int v;
    qsort((void *)entries, 10, sizeof(struct record), (compfunc)compare);
    struct record *p = entries;
    for(v=0;v<counter;v++, p++)
    {
         printf("%s ..... %d \n", p->player , p->gp);
    }
}

int compare(struct record * p1, struct record * p2)
{
     if( p1->gp < p2->gp)
         return -1;
     else if (p1->gp > p2->gp)
         return 1;
     else
         return 0;
}

Edit: Hey everyone thanks so much for all your help but, I have tried everything you guys have said and it still just turns everything value to zero

like image 876
user2322610 Avatar asked Mar 25 '26 09:03

user2322610


1 Answers

Your call can be simplified, no need to cast to void *:

qsort(entries, 10, sizeof entries[0], compare);

Note use of sizeof entries[0] to avoid pointless repetition of the array type.

There should be no cast of the comparison function either, since it should simply be defined to match the prototype:

static int compare(const void *a, const void *b)
{
  const struct record *ra = a, *rb = b;

  if( ra->gp < rb->gp)
     return -1;
  if (ra->gp > rb->gp)
     return 1;
  return 0;
}

By the way, just to be informational, here's a classic (?) way to tersify the 3-way testing that you sometimes see in places like these:

return (ra->gp < rb->gp) ? -1 : (ra->gp > rb->gp);

I do not argue for this way of expressing it, especially not if you're a beginner, but thought I'd include it since it's relevant and might be instructional to have seen.

like image 156
unwind Avatar answered Mar 28 '26 01:03

unwind