简体   繁体   English

指向c中函数的指针

[英]working of pointer to functions in c

Please look at the code following:- 请查看以下代码: -

 #include <stdio.h>
 int sum ( int b, int a){
 return (a+b);
  }
 int main(){
 int (* funptr)( int , int ) = sum;
 int a = ( * funptr )( 4,5);
 int b = funptr (4,5);
 printf("%d\n%d",a,b);
 return 1;
 }

Is there any difference between the two function calling via pointer,one is 通过指针调用两个函数之间是否有任何区别,一个是

int a = ( * funptr )( 4,5);

and another is 另一个是

int b = funptr (4,5);

As i have compiled this code and result is same in both the cases.Is this means that these are equivalent? 因为我编译了这个代码,结果在两种情况下是相同的。这是否意味着它们是等价的?

Due to historic differences how to take the address of a function, you can apply address of and dereference any time you want to a function name, without any effect whatsoever. 由于历史差异如何获取函数的地址,您可以随时应用地址和取消引用功能名称,而不会产生任何影响。

Also, dereferencing a function pointer has no effect at all. 此外,取消引用函数指针根本不起作用。

So, yes, your examples are equivalent. 所以,是的,你的例子是等价的。

In case of function pointer: 在函数指针的情况下:

Function Pointer is very flexible to use.. You can put value into it with or without the & operator, and call the stored function through pointer with or without * operator. Function Pointer使用起来非常灵活。您可以在有或没有&运算符的情况下将值放入其中,并通过带或不带*运算符的指针调用存储的函数。

eg, 例如,

int (* funptr)( int , int ) = sum;   // or int (* funptr)( int , int ) = &sum;
int a = ( * funptr )( 4,5);          // or int a = funptr( 4,5);

Hope it helped... 希望它有所帮助......

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

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