c函数指针
C Function Pointer
A function pointer is a pointer that contains the address of a function. It can be declared in following way. You must follow the same syntax for declaration otherwise you will get an error.
Syntax
return_type (* pointer_name) (argument_list);
Example
int (*p) (int, int);
In above example we are declaring a pointer to function or a function pointer that will contain the address of a function with return type integer and having two integer arguments.
The above function pointer p can be assigned address of a function and can call that function in following way. Lets assume the function with name fun1().
As you can see in above example that function pointer can be assigned address and can call a function in two ways. You can use any one of them.
Lets make one program that will calculate addition of two numbers using the concept of function pointer in C.
#include<stdio.h>
int add(int a,int b)
{
return a+b;
}
void main()
{
int (*p)(int,int);
p=&add;
printf("Sum=%dn",(*p)(5,3));
}
Output
Explanation
1. Firstly I have made a function add() that will take two integer arguments, calculate their addition and return the result.
2. Now in the main() function I am declaring a function pointer p and then storing the address of function add(). This can be done without using the address of operator i.e. &.
3. Finally I am calling the function using the function pointer and then displaying the result. As I have already mentioned above that the calling can also be done in two ways. So here we can call the function by simply writing p(5,3).
Below I have added a video that will help you in understanding the concept of function pointer or pointer to function in C.
C function pointer is an advance topic of pointer and a little bit difficult too. If you have any kind of queries then please mention it in comments.
翻译自: https://www.thecrazyprogrammer.com/2015/02/c-function-pointer.html
c函数指针

1147

被折叠的 条评论
为什么被折叠?



