//main.c
#include<stdio.h>
#include<stdlib.h>
int (*fp)(int,int); //declare a variable
typedef int (*tfp)(int,int); //define a type function pointer
int add(int rnum,int lnum)
{
return rnum+lnum;
}
int main()
{
tfp tfun = add;
fp = add;//variable assignment
printf("fp(1,2)= %d\n",(*fp)(1,2)); //指针的内容为函数的地址
printf("tfun(1,2)= %d\n",(*tfun)(1,2));//指针的内容为函数的地址
printf("fp(1,2)= %d\n",fp(1,2)); //指针本身也是函数的首地址
printf("tfun(1,2)= %d\n",tfun(1,2));//指针的内容为函数的地址
return 0;
}
程序编译输出为
samba_share]# gcc main.c
[root@localhost samba_share]# ./a.out
fp(1,2)= 3
tfun(1,2)= 3
fp(1,2)= 3
tfun(1,2)= 3
[root@localhost samba_share]#
函数指针
最新推荐文章于 2025-11-01 00:03:12 发布
本文通过一个C语言程序示例介绍了如何定义和使用函数指针,包括声明函数指针变量、定义函数指针类型及如何将函数赋值给函数指针变量,并演示了如何调用这些函数指针所指向的函数。

411

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



