以下代码使用 gcc 编译和运行良好。但我想知道这样的 union 是否由标准定义,以及它是否以相同的方式在所有 c 编译器上工作。我知道如果函数的参数不是指针并且彼此不兼容,那将不起作用,但只要所有参数都是指针并且参数数量相同,就不会有问题,或者?
typedef struct node {
unsigned long int key;
} node_t;
typedef struct node1 {
unsigned long int key;
char *str;
} node1_t;
typedef struct node2 {
unsigned long int key;
void *data;
} node2_t;
typedef struct node3 {
unsigned long int key;
int numbers[256];
} node3_t;
int compare(node_t *a, node_t *b) {
printf("%ld ? %ld\n", c->key, d->key);
return c->key == d->key;
}
struct comp {
union {
int (*c0) (node_t *a, node_t *b);
int (*c1) (node1_t *a, node1_t *b);
int (*c2) (node1_t *a, node2_t *b);
int (*c3) (node1_t *a, node3_t *b);
int (*c4) (node2_t *a, node1_t *b);
int (*c5) (node2_t *a, node2_t *b);
int (*c6) (node2_t *a, node3_t *b);
int (*c7) (node3_t *a, node1_t *b);
int (*c8) (node3_t *a, node2_t *b);
int (*c9) (node3_t *a, node3_t *b);
} are;
};
int main(int argc, char *argv[])
{
node1_t a[] = {
{ 23477843258923UL, "Hello World" },
{ 10254892378892UL, "Hello Back" }
};
node2_t b[] = {
{ 83296783479803UL, NULL },
{ 52348237489832UL, (void *) &a[1] }
};
node3_t c[] = {
{ 91308823949203UL, { 3, 4, 5 } },
{ 17587832478823UL, {43, 43, 43, 86 } }
};
struct comp comp;
comp.are.c0 = compare;
comp.are.c1(&a[0], &a[1]);
comp.are.c2(&a[1], &b[0]);
comp.are.c3(&a[0], &c[1]);
comp.are.c8(&c[1], &b[1]);
}
最佳答案
union
是有效的,但您使用它所做的却不是。你不能用一种类型将某些东西放入 union
中,然后像 main
的结尾那样将它与另一种类型一起使用,除非这些类型是可转换的(感谢@Christoph 的评论).
关于c - 指向 union 中允许的类似布局的功能的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5124878/