0

I have a structure

struct employee {
    int record;
    int ID;
....
};

employee * arr = (employee*) malloc(501 * sizeof (employee));

And i need to sort it by this two parameters (ID at first and record as the second). I'm using standart Qsort with

 qsort (employee, records, sizeof(employee), compare);

But i dont know, how to edit basic compare function, to make it works

I have samething like this

int comparestruct(const employee *p1, const employee *p2)
{
    const struct employee *elem1 = p1;    
    const struct employee *elem2 = p2;

   if ( elem1->ID < elem2->ID)
      return -1;
   else if (elem1->ID > elem2->ID)
      return 1;
   else
      return 0;
}

But this isn't working...

Any help please?

4
  • 2
    How could it possibly work if you don't even mention the record field? (And what is zam? Should be void.) Commented Nov 22, 2014 at 20:10
  • typecast p1 and p2 to employee? not sure if there is some kind of inheritance there or how zam relates to an employee Commented Nov 22, 2014 at 20:13
  • zam means employee, i translated it to english and forget this.. Commented Nov 22, 2014 at 20:23
  • Why are you passing employee (struct name) in the qSort like qSort(employee, ...? it should be passed an instance of an array. Commented Nov 22, 2014 at 20:29

1 Answer 1

0

The usual way would be something like:

int comparestruct(const void *a_, const void *b_) {
    const struct employee *a = a_;
    const struct employee *b = b_;
    int rv = a->ID - b->ID;
    if (rv == 0) rv = a->record - b->record;
    return rv;
}

Of course, this has a subtle bug if the subtractions might overflow (which depends on the range of your IDs and record numbers.) If that is a possible problem, you might need:

int comparestruct(const void *a_, const void *b_) {
    const struct employee *a = a_;
    const struct employee *b = b_;
    if (a->ID < b->ID) return -1;
    if (a->ID > b->ID) return 1;
    if (a->record < b->record) return -1;
    if (a->record > b->record) return 1;
    return 0;
}

instead

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.