使用qsort对2D数组排序时发出警告 [英] Warning while sorting a 2D array with qsort
问题描述
我正在尝试使用qsort
在C中对2D数组进行排序.排序有效,但出现警告:
I'm trying to use qsort
to sort a 2D array in C. The sort works, but I get the warning:
warning: initialization discards 'const' qualifier from pointer target type [enabled by default]
如何修改我的比较函数以消除警告(假设qsort
需要参数const void *pa, const void *pb
?
How can I modify my compare function to eliminate the warning (given that qsort
requires the parameters 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上阅读了这篇文章,但是我仍然不确定如何更改比较功能.
I've read this post on Stack Overflow, but I'm still not sure how I should alter the compare function.
我有一个看起来像这样的数组:
I have an array that looks like this:
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后按第二列对2d数组进行排序.
Except in the second column, instead of zeroes, those are filled with other numbers. I'm trying to sort this 2d array by the second column, after 0s are filled in.
推荐答案
您可以使用decls,但是最终我认为这足以满足您使用的比较器的需求:
You could toy with the decls, but in the end I think this will suffice for the comparator you're using:
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]);
}
您的数据项目"仅是2D数组中的int[]
偏移量.如果这是一个 pointer 数组,而不是真正的2D数组,那将有很大的不同. Grijesh非常接近这一点,只缺少了[1]
偏移量(和简单的数学运算),如果他删除删除的答案来解决这个问题,我会删除它.
Your data "items" are nothing more than int[]
offsets in a 2D array. Were this a pointer array rather than a genuine 2D array, this would be considerably different. Grijesh was very close to this, only missing the [1]
offsets (and the simple math), and if he undeletes his answers to fix it I'll just drop this.
这篇关于使用qsort对2D数组排序时发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!