且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C:如何访问存储在void指针(void *)中的函数指针?

更新时间:2023-11-08 18:14:34

这是 operator优先级 :函数调用操作符的优先级高于强制转换操作符.

It's a matter of operator precedence: The function call operator have higher precedence than the casting operator.

这意味着您的表达式(int (*)(int)) functions[0](x)确实等于(int (*)(int)) (functions[0](x)).

That means your expression (int (*)(int)) functions[0](x) is really equal to (int (*)(int)) (functions[0](x)).

您需要在正确的位置显式添加括号以强制转换指针:((int (*)(int)) functions[0])(x).

You need to explicitly add parentheses in the correct places to cast the pointer: ((int (*)(int)) functions[0])(x).

一个更好的IMO解决方案是使用一个指向函数的指针数组 ,因此该数组元素已经是正确的类型:

A much better solution IMO would be to have an array of pointers to functions, so the array elements already is of the correct type:

typedef int (*function_ptr)(int);

function_ptr functions[] = { ... };

然后不需要强制转换:functions[0](x).

Then no casting is needed: functions[0](x).

然后,您也可以免受伦丁的答案中提到的问题.

Then you also would be safe from the issues mentioned in the answer by Lundin.