值和函数指针的联合 [英] union of value and function pointer
问题描述
我正在努力使用工会.为什么我无法将函数指针传递到联合所在的位置?任何帮助将不胜感激.
I am struggling with using unions. Why am I unable to pass the function pointer to where the union would be? Any help would be greatly appreciated.
删除了一个 typedef
removed a typedef
#include <stdio.h>
union U {
int(*fnPtr)(int);
int i;
};
enum E {
OPTION_0 = 0,
OPTION_1 = 1
};
int multiply_by_two (int x) {
return 2 * x;
}
int f (int x, enum E e, union U u) {
switch (e) {
case OPTION_0:
/* Return the sum */
return x + u.i;
case OPTION_1:
/* Return 2 * x */
return u.fnPtr (x);
}
}
int main (void) {
int a;
scanf ("%d", &a);
int b = f (a, OPTION_1, &multiply_by_two);
printf ("%d\n", b);
return 0;
}
推荐答案
首先,这个定义无效:
union U {
typedef int(*fnPtr)(int);
int i;
};
struct
或 union
中不能有 typedef
.删除 typedef 会给你一个正确的定义:
You can't have a typedef
inside of a struct
or union
. Removing the typedef will give you a proper definition:
union U {
int(*fnPtr)(int);
int i;
};
第二个问题在这里:
int b = f (a, OPTION_1, &multiply_by_two);
函数 f
需要一个 union U
,但你传递给它的是 int (*)(int)
.这些类型不兼容.仅仅因为联合具有该类型的成员并不意味着您可以在任何使用联合的地方使用该类型.您需要创建一个联合,设置适当的字段,然后将其传递给函数.
The function f
expects a union U
, but you're passing it a int (*)(int)
. Those types are not compatible. Just because the union has a member of that type doesn't mean you can use that type wherever you would use the union. You need to create a union, set the proper field, then pass that to the function.
union U u;
u.fnPtr = multiply_by_two;
int b = f (a, OPTION_1, u);
这篇关于值和函数指针的联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!