这是C语言。当我运行我的以下程序时,无论我给出的值多少,我都会收到运行时分段错误错误。请帮我找出原因。给出分段错误的位域
#include <stdio.h>
#include <stdlib.h>
struct date
{
unsigned day:
5;
unsigned month:
4;
unsigned year:
12;
};
struct emp
{
char name[10];
struct date d;
};
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 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;
}
C中的Bitfields有很多怪癖,所以我会建议你避免它们,除非你真的需要它们。对于上面的代码,你可以使用'struct date {uint8_t day; uint8_t月; uint16_t年; };',并且您可能会得到相同或更高性能的结构,并且功能更多(可以使用成员地址)。 – user694733