c函数指针_C函数指针

c函数指针

We declare a pointer to integer, pointer to character or pointer to array. Similarly we can declare a pointer to function or a function pointer. Same as like variables, functions also have some address in memory.

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函数指针

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值