简体   繁体   English

如何在C中使用函数的指针? (没有C ++)

[英]How to use the pointer of a function in C? (No C++)

As the title says, how do I use the pointer of a function in C? 正如标题所说,我如何在C中使用函数的指针? Can I just take the address of the function name and pass it to another function; 我可以只获取函数名的地址并将其传递给另一个函数; then dereference it and call it? 然后取消引用并调用它?

Thanks a lot. 非常感谢。

If you know the function address, then yes. 如果您知道函数地址,那么是。 For example: 例如:

int add(int a, int b)
{
    return a + b;
}

int sub(int a, int b)
{
    return a - b;
}

int operation(int (*op)(int, int), int a, int b)
{
    return op(a, b);
}

Then just call it like this: 然后就这样称呼它:

printf("%d\n", operation(&add, 5, 3)); // 8
printf("%d\n", operation(&sub, 5, 3)); // 2

You can even do some array tricks: 你甚至可以做一些数组技巧:

int op = 0;
int (*my_pointer[2])(int, int) =
{
    add, // op = 0 for add
    sub  // op = 1 for sub
};
printf("%d\n", my_pointer[op](8, 2)); // 10

well to answer your question precisely, there is a provision in C for such needs which is called " function pointer ". 很好地回答你的问题,C中有一个规定可以满足这种需求,即“ 函数指针 ”。

But you have to follow certain rules, 但你必须遵循一定的规则,

1) All the functions you want to call using function pointer must have same return type. 1)要使用函数指针调用的所有函数必须具有相同的返回类型。 2) All the functions you want to call using function pointer must have same no of arguments and argument types. 2)要使用函数指针调用的所有函数必须具有相同的参数和参数类型。

For example, 例如,

int add(int, int); int add(int,int); int sub(int, int); int sub(int,int);

for above two functions you can write function pointer as, 对于以上两个函数,您可以将函数指针写为,

int (*operation)(int , int); int(* operation)(int,int);

and you can use it just as described by Flavio Torbio . 你可以像Flavio Torbio所描述的那样使用它。

hope it helps..... 希望能帮助到你.....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM