c - 指向 union 中允许的类似布局的功能的指针?

标签 c struct function-pointers unions

以下代码使用 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/

相关文章:

c++ - AVL树的中序遍历,将值保存在数组中

c++ - 结构的 Xcode typedef 创建错误/警告

C - 在可变函数中将多个函数地址作为参数传递

c - 在结构中的数组末尾填充

c++ - 在哪里可以找到 __sync_add_and_fetch_8?

c++ - 如何在 C++ 中调用泛型结构

c - 将 C++ lambda 传递给旧的 C 函数指针

c - printf 格式字符串最大宽度值(填充)%(??)d%n

c - 指向函数指针数组的指针

c++ - 成员函数,无法推导 ‘auto’