Reputation: 854
i have an array of structures (Employee):
typedef struct Employee{
char name[MAX_SIZE];
int salary;
int experience;
} employee_t;
i want to reorder my array by salary, i have created a comperator:
int compareEmployeesBySalary(const void* a, const void* b){
employee_t* one = (employee_t*)a;
employee_t* two = (employee_t*)b;
if (one->salary == two->salary)
return 0;
else if (one->salary > two->salary)
return 1;
else
return -1;
}
void main()
{
int i;
employee_t** employeeArray = (employee_t**)malloc(sizeof(employee_t*)*5);
for(i=0 ; i < 2 ; i++)
{
employeeArray[i] = (employee_t*)malloc(sizeof(employee_t));
readEmployee( employeeArray[i] ); //input for 5 employee's
}
puts("");
puts("beforesort\n");
for(i=0; i <2 ; i++)
{
printEmployee(employeeArray[i]);
}
puts("--------------------------------------------------------");
puts("after salary sort\n");
qsort(&employeeArray, 2, sizeof(employee_t), compareEmployeesBySalary);
for(i=0; i < 2 ; i++)
printEmployee( employeeArray[i] );
}
when i run it normally it just prints the original array by the order i insert the employees, but when im debugging it prints by my compare function, why is that?
thank you!!!
Upvotes: 0
Views: 254
Reputation: 21213
You need to change this:
qsort(&employeeArray, 2, sizeof(employee_t), compareEmployeesBySalary);
To:
qsort(employeeArray, 2, sizeof(employee_t *), compareEmployeesBySalary);
The first argument must be employeeArray
because the qsort()
function receives a pointer to the start of the array, not a pointer to a pointer to the start of the array. Plus, you have an array of pointers, not an array of employee_t
, so the 3rd argument must be sizeof(employee_t *)
.
Finally, change your compare function to:
int compareEmployeesBySalary(const void* a, const void* b){
employee_t* one = *(employee_t **)a;
employee_t* two = *(employee_t **)b;
if (one->salary == two->salary)
return 0;
else if (one->salary > two->salary)
return 1;
else
return -1;
}
Because again, what you have is an array of pointers, so a
and b
will be of type employee_t **
.
Upvotes: 5
Reputation: 3834
One thing I see is that you pass sizeof(employee_t)
into the size parameter of qsort, whereas your array only stores pointers to employee_t
. I suggest you try replacing sizeof(employee_t)
in qsort
with sizeof(employee_t*)
.
Upvotes: 0