C qsort 不对多维数组中的最后一项进行排序

C qsort not sorting last item in multidimensional array

我正在使用 C 中的 qsort 函数对 3 列整数进行排序。它对我的二维数组进行了很好的排序,除了最后一项


这是我的代码:

#include <stdio.h>
#include <stdlib.h>

#define ARRAYSIZE 10

int array[ARRAYSIZE][3];

static int x_then_z(const void *a, const void *b) {
    const int *arr1 = (const int*)a;
    const int *arr2 = (const int*)b;
    int diff1 = arr1[0] - arr2[0]; //x
    if(diff1) return diff1;
    return arr1[2] - arr2[2]; //z
}

static int z_then_x(const void *a, const void *b) {
    const int *arr1 = (const int*)a;
    const int *arr2 = (const int*)b;
    int diff1 = arr1[2] - arr2[2]; //z
    if(diff1) return diff1;
    return arr1[0] - arr2[0]; //x
}

void print_array() {
    for(int i = 0; i < ARRAYSIZE; i++){
        printf("%d, %d, %d\n", array[i][0], array[i][1], array[i][2]);
    }
}

int main(int argc, char *argv[]){
    fill_array();
    //print_array();
    //printf("\n");

    qsort(array, ARRAYSIZE, 3*sizeof(int), x_then_z);
    fprintf(stderr, "Sorted by x then z\n");
    print_array();

    printf("\n");

    qsort(array, ARRAYSIZE, 3*sizeof(int), z_then_x);
    fprintf(stderr, "Sorted by z then x\n");
    print_array();

    return EXIT_SUCCESS;
}

我将我的列命名为 x, y and z(以免在我有 a and b 的比较函数中混淆自己)。 fill_array 函数用以下计算输入填充数组:

31, 56, 8  
39, 71, 9  
65, 76, 10  
64, 129, 12  
44, 191, 14  
105, 199, 15  
169, 319, 19  
44, 321, 18  
319, 364, 22  
295, 551, 25  

然而,输出是这样的:

Sorted by x then z  
31, 56, 8  
39, 71, 9  
44, 191, 14  
44, 321, 18  
64, 129, 12  
65, 76, 10  
105, 199, 15  
169, 319, 19  
319, 364, 22  
**295, 551, 25**  

Sorted by z then x  
31, 56, 8  
39, 71, 9  
65, 76, 10  
64, 129, 12  
44, 191, 14  
105, 199, 15  
44, 321, 18  
169, 319, 19  
319, 364, 22  
295, 551, 25  

可以看到数组的最后一个值没有排序。如果我将 ARRAYSIZE 更改为更大的数字,则数组中的最后一个值不会排序。我哪里错了?

fill_array 函数有一个 off by 1 错误。填充数组时,它是从 1 开始的,而不是 0