如何一起处理位域和 qsorting?

How do I handle bitfields and qsorting together?

语言是C。 最近在这里,我请求并获得帮助,使函数 qsort 适用于结构数组。

我现在正在研究位域并尝试制作一个程序,该程序使用一个结构,该结构使用另一个使用位域的结构,然后将其整理出来。但是当我编译它时,我在 "dereferencing pointer to incomplete type" 的比较函数中出错,我又进行了多次试验,但仍然无法使其工作。你们能帮帮我吗?

代码如下:

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

int compare(const void * a, const void * b)
{
    struct emp *orderA = (struct emp *)a;
    struct emp *orderB = (struct emp *)b;

    return (orderA->d.year - orderB->d.year);
}

int main()
{
    int i;
    struct date{
        unsigned day : 5;
        unsigned month : 4;
        unsigned year : 12;
    };

    struct emp {
        char name[10];
        struct date d;
    };

    struct emp e[5];
    for(i = 0; i < 5; i++)
    {
        scanf("%s %d %d %d", e[i].name, e[i].d.day, e[i].d.month, e[i].d.year);
    }
    qsort(e, 5, sizeof(struct emp), compare);

    for(i = 0; i < 5; i++)
    {
        printf("%s %d %d %d\n", e[i].name, e[i].d.day, e[i].d.month, e[i].d.year);
    }
    return 0;
}

为什么这不起作用

由于您在 main 函数中定义了 struct emp,它仅存在于 main 函数中。

因此,当您尝试在 compare 函数中转换为 struct emp* 时,类型不存在。

如果你想让这段代码起作用,你应该移动

struct emp {
    char name[10];
    struct date d;
};

在你的主要功能之外,在你的比较功能之上。

理想情况下,您应该将其移动到自己的头文件中并包含它。

这同样适用于您的 struct date,因为它在 struct emp 中使用。所以移动

struct date{
    unsigned day : 5;
    unsigned month : 4;
    unsigned year : 12;
};

你的 main 函数也是如此。


C 中的作用域

请记住,作为 C 中的一般规则,任何在范围内声明或定义的非静态标识符(意思是在一组 {} 之间)对于该范围都是本地的,不能在该范围外访问范围。