C:如何访问存储在void指针(void *)中的函数指针? [英] C: How to access a function pointer stored in a void pointer (void *)?
问题描述
对于如何访问存储在void指针(void *)中的函数指针感到困惑.
Confused as to how one can access a function pointer stored in a void pointer (void *).
假设您有这个:
void *functions[] =
{
&sqrt, // int ft_sqrt(int nb);
&power,
&logN,
&factorial;
};
// An array of void pointers, each storing a function pointer.
如果我想访问sqrt
函数,我的猜测将是:
If I wanted to access the sqrt
function, my guess would be the following:
(int (*)(int)) functions[0](x)
但是我的猜测是错误的:
But my guess is wrong:
error: called object type 'void *' is not a function or function pointer
那么如何访问这些功能之一?
So how would one access one of these functions ?
推荐答案
这是 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.
这篇关于C:如何访问存储在void指针(void *)中的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!