1

我正在尝试用qsortC 对二维数组进行排序。排序有效,但我收到警告:

warning: initialization discards 'const' qualifier from pointer target type [enabled by default]

如何修改我的比较功能以消除警告(鉴于qsort需要参数const void *pa, const void *pb

int cmp (const void *pa, const void *pb ) {
  const int (*a)[2] = pa; // warning here
  const int (*b)[2] = pb; // warning here
  if ( (*a)[1] < (*b)[1] ) return 1;
  if ( (*a)[1] > (*b)[1] ) return -1;
  return 0;
}

我已经在 Stack Overflow 上阅读了这篇文章,但我仍然不确定应该如何更改比较函数。

我有一个看起来像这样的数组:

int letterCount[26][2] = {{0, 0},{1, 0},{2, 0},{3, 0},{4, 0},{5, 0},{6, 0},{7, 0},{8, 0},{9, 0},{10, 0},{11, 0},{12, 0},{13, 0},{14, 0},{15, 0},{16, 0},{17, 0},{18, 0},{19, 0},{20, 0},{21, 0},{22, 0},{23, 0},{24, 0},{25, 0}};

除了在第二列中,它们不是零,而是用其他数字填充。在填充 0 之后,我试图按第二列对这个二维数组进行排序。

4

2 回答 2

0

这应该怎么做(*a)[2]?您似乎在声明中取消引用指向数组的指针。由于缺乏更好的事情可做,我写了自己的版本,希望对您有所帮助:

#include <time.h>
#include <stdio.h>
    void Qsort(int matrix[][2] , int lenght)
    {
        if(!lenght)
                return;
        int temp = 0 , pivot , b = 0 , e = lenght - 1 , test = 0;
        const int MIN =0 , MAX = e;
        srand(time(NULL));
        test = (rand() % (MAX - MIN + 1)) + MIN;
        pivot = matrix[test][1];
        while(b < e)
        {
            while(matrix[b][1] < pivot)
                b++;
            while(matrix[e][1] > pivot)
                e--;
            temp = matrix[b][1];
            matrix[b][1] = matrix[e][1];
            matrix[e][1] = temp;
        }
        Qsort(matrix , b);
        Qsort(&(matrix)[b + 1] , lenght - 1 - b);

    }
于 2013-09-22T18:45:30.940 回答
0

你可以玩弄 decls,但最后我认为这对于你使用的比较器就足够了:

int cmp (const void *pa, const void *pb )
{
    const int *a = pa;
    const int *b = pb;
    if (a[1] < b[1]) 
        return -1;
    return (b[1] < a[1]);
}

您的数据“项目”只不过int[]是二维数组中的偏移量。如果这是一个指针数组而不是真正的 2D 数组,这将是相当不同的。Grijesh 非常接近这一点,只缺少[1]偏移量(和简单的数学运算),如果他取消删除他的答案来修复它,我就会放弃这个。

于 2013-09-22T19:19:27.863 回答