我想知道Code
结构中传递给qsort的每个元素的大小是由sizeof(Code)
还是sizeof(Code *)
决定的。无论哪种方式似乎都有效。 malloc(sizeof(Emp *))
或malloc(sizeof(Emp))
我在这个排序算法上做错了吗?
#include <stdio.h>
#include <stdlib.h>
typedef struct CODE{
void *ecode;
} Code;
typedef struct EMP{
Code *codes;
int total;
} Emp;
int *decptr(int n){
int *p = malloc(sizeof(int));
*p = n;
return p;
}
int orderEmp(const void *p1, const void *p2){
const Code *q1 = p1;
const Code *q2 = p2;
int r = (*(int *) q1->ecode);
int s = (*(int *) q2->ecode);
return (r<s)-(r>s);
}
Emp *sortEmp(Emp *employee, int total){
// sizeof(Code) vs sizeof(Code*)?
qsort(employee->codes, total, sizeof(Code), orderEmp);
}
#define NUM 20
int main(){
int i;
// sizeof(Emp) vs sizeof(Emp *)?
Emp *employee = malloc(sizeof(Emp));
employee->total = 0;
// sizeof(Code) vs sizeof(Code *)?
employee->codes = calloc(NUM, sizeof(Code));
for(i = 0; i < NUM; i++){
employee->codes[i].ecode = decptr(i);
employee->total++;
}
sortEmp(employee, employee->total);
for(i = 0; i < NUM; i++){
printf("%d\n", (*(int *) employee->codes[i].ecode));
}
return 0;
}