投射3D阵列的比较功能

时间:2013-11-14 11:34:26

标签: c casting multidimensional-array

我已经删除了一个类似的问题(对不起,如果有人回答),我找到了一个解决方案,在此比较函数中跳过警告(迂腐旗帜):

int comp(const void *pa, const void *pb)
{
    const int (*a)[2] = pa;

警告:

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

使用演员解决:

const int (*a)[2] = (void * const)pa;

完整的代码:

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

int comp(const void *pa, const void *pb)
{
    const int (*a)[2] = (void * const)pa;
    const int (*b)[2] = (void * const)pb;

    return (a[0][0] + a[1][0]) - (b[0][0] + b[1][0]);
}

int main(void)
{
    int a[][2][2] = {
        {{1,2},{3,4}},
        {{3,4},{5,6}},
        {{2,3},{4,5}},
    };
    size_t i, n = sizeof(a) / sizeof(a[0]);

    for (i = 0; i < n; i++) {
        printf("%d\n", a[i][0][0] + a[i][1][0]);
    }
    qsort(a, n, sizeof(a[0]), comp);
    printf("Sorted:\n");
    for (i = 0; i < n; i++) {
        printf("%d\n", a[i][0][0] + a[i][1][0]);
    }
    return 0;
}

现在它似乎按预期工作而没有警告,但我不明白演员, 为什么(void * const)pa代替(const void *)pa

1 个答案:

答案 0 :(得分:1)

我无法解释为什么gcc没有做到这一点。 const void*表示指向不可修改数据的无类型指针。不要与void * const混淆,int const (*a)[2] = (int const (*)[2])pa; 是指向无类型数据的不可修改的指针。您的声明应该工作。

但是,唉,在紧要关头,这样做:

{{1}}

与第二个参数同样如此。很可怕,但至少它会压制你的警告。如果我发现为什么会发生这种情况,或者一些更聪明的占卜者想要发声,我会确定并发回这里。

一切顺利。