C 中的匿名联合

Anonymous union in C

我正在尝试了解我所拥有的用例的匿名联合。用例是能够在函数指针 table 中使用给定方法的不同原型。例如,在下面的代码片段中,myfunc 可以有两个变体,一个只接受一个字符串;和一个可以接受额外参数的。

这是我的代码片段-

typedef struct my_struct
{
    union{
            int (*myfunc)(char*);
            int (*myfuncEx)(char*, int);
    };

}my_struct_t;

int myfunc_imp(char* x)
{
    printf("This is myfunc_imp - %s\n", x);
}

int myfuncEx_imp(char* x, int y)
{
    printf("This is myfuncEx_imp - %s\n", x);
    printf("This is myfuncEx_imp - %d\n", y);
}

int main()
{
    char *string = "Hello World";
    my_struct_t me1, me2;
    me1.myfunc = myfunc_imp;
    me1.myfunc(string);

    me2.myfuncEx = myfuncEx_imp;
    me2.myfuncEx(string, 7);

    static const me3 = {myfuncEx_imp};
    me3.myfuncEx(string, 8);

    return 0;
}

示例 me1 和 me2 似乎提供了正确的结果。 但是以我为例。在我试图静态初始化结构内的联合的地方,抛出这个错误-

warning: initialization makes integer from pointer without a cast
error: request for member `myfuncEx' in something not a structure or union

谁能指出在结构中初始化匿名联合的正确方法。

编辑:我以非常明显错误的方式声明结构错误,正确的方式-

static const my_struct_t me3 = {myfuncEx_imp};

我运行昨天进入了这个。您不能在不指定联合成员的情况下初始化联合。否则就是模棱两可的。所以,

static const my_struct_t me3 = { .myfuncEx = myfuncEx_imp };