qsort不会改变我的数组顺序

时间:2015-09-03 16:29:03

标签: c function structure

我有一组结构(员工):

typedef struct Employee{
    char name[MAX_SIZE];
    int salary;
    int experience;
} employee_t;

我想按工资重新排序我的数组,我创建了一个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] );
}

当我正常运行时它只是按照我插入员工的顺序打印原始数组,但是当我调试时它会通过我的比较功能打印, 那是为什么?

谢谢!!!

2 个答案:

答案 0 :(得分:5)

你需要改变这个:

qsort(&employeeArray, 2, sizeof(employee_t), compareEmployeesBySalary);

要:

qsort(employeeArray, 2, sizeof(employee_t *), compareEmployeesBySalary);

第一个参数必须是employeeArray,因为qsort()函数接收到指向数组开头的指针,而不是指向指向数组开头的指针。另外,你有一个指针数组,而不是employee_t的数组,所以第三个参数必须是sizeof(employee_t *)

最后,将比较功能更改为:

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;
}

因为您所拥有的是一系列指针,因此ab的类型为employee_t **

答案 1 :(得分:0)

我看到的一件事是你将sizeof(employee_t)传递给qsort的size参数,而你的数组只存储指向employee_t的指针。我建议您尝试使用sizeof(employee_t)替换qsort中的sizeof(employee_t*)