为什么 qsort int 数组降序排列不正确?

sho*_*umm 1 c qsort

我尝试编写比较函数来对 int 数组进行排序。它给出了升序的正确结果。但对于降序排列是不正确的。为什么?什么是正确的比较 int 函数?

int compare(const void *a, const void *b){
    int x = *(int*)a;
    int y = *(int*)b;
    return (x > y) - (x < y);
}

int reverse(const void *a, const void *b){
    return -compare(a, b);
}

int main(){
    int x[] = {500, 456, 18, 13, 3, 89, 800, 6874};
    qsort(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), reverse);
    for (int i=0; i < sizeof(x)/sizeof(x[0]); i++){
    printf("%d\n", x[i]);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我期望打印的整数按降序排列,从最大的 6874 到最小的 3。但我收到的却是:

800 6874 500 456 18 13 3 89

Chr*_*odd 5

您已经交换了 qsort 的第二个和第三个参数 - 应该是

qsort(x, sizeof(x)/sizeof(x[0]), sizeof(x[0]), reverse);
Run Code Online (Sandbox Code Playgroud)

你调用它的方式,因为你的数组恰好有 8 个元素,而 sizeof(int) 在你的机器上恰好是 4,所以它根据每对的第一个 int 对 int 对进行排序。