Linux/C 高级——函数指针

1.概念

本质时指针,指向了函数。类比着数组指针。

数组指针:本质是指针,指向了数组的指针。

数组指针定义格式:数据类型 (*指针名)列数;

int a23;

int (*p)3 = a;

//pij *(pi+j) *(*(p+i)+j)

2.定义格式

2.1概念

数据类型 (*指针名)(参数列表);
函数名:函数地址

2.2基本用法

#include <stdio.h>

int add(int a, int b) //add: 函数名,也就是函数的地址

{

return a + b;

}

int sub(int a, int b)

{

return a - b;

}

int main(int argc, char const *argv\[\])

{

int (*p)(int, int); //定义函数指针, 类型int (*)(int,int)

p = add;

printf("%d\n", p(1, 2));

printf("%d\n", add(1, 2));

p = sub;

printf("%d\n", p(1, 2));

printf("%d\n", sub(1, 2));

return 0;

}
把函数指针当成餐宿传递给函数:
一种接口,多种方法:
#include <stdio.h>

int add(int a, int b) //add: 函数名,也就是函数的地址

{

return a + b;

}

int sub(int a, int b)

{

return a - b;

}

int test(int (*p)(int, int), int a, int b) //p=add, a=5, b=6

{

return p(a, b); //add(5,6);

}

int main(int argc, char const *argv\[\])

{

printf("%d\n", test(add, 5, 6)); //11

printf("%d\n", test(sub, 5, 6)); //-1

return 0;

}

结构体内成员是函数指针(不常用但是看内核原码可能会见到)
#include <stdio.h>

struct test

{

int (*p)(int,int);

};

int add(int a,int b)

{

return a+b;

}

int main(int argc, char const *argv\[\])

{

struct test x;

x.p = add;

printf("%d\n", x.p(1,2));

return 0;

}

3.函数指针数组

3.1概念

本质是数组,数组中元素是函数指针

3.2定义格式

数据类型 (*数组名元素个数)(形参列表);
数据类型:和指向的函数返回值类型一致

形参列表:和指向的函数参数一致

3.3赋值

int (*arr3)(int,int) = {函数名};
#include <stdio.h>

int add(int a, int b) //add: 函数名,也就是函数的地址

{

return a + b;

}

int sub(int a, int b)

{

return a - b;

}

int main(int argc, char const *argv\[\])

{

int (*arr2)(int, int) = {add, sub}; //函数指针数组

printf("%d %d\n", arr0(1, 2), arr1(3, 4));

return 0;

}
练习:
a) 一个整型数

int a;

b) 一个指向整型的指针

int *p=&a;

c)一个指向指针的指针,它指向的指针是一个指向一个整型数

int **q=&p;

d)一个有10个整型数的数组

int arr10;

e)一个有10个指针的数组,该指针是指向一个整型数的

int *a10;

f)一个指向有10个整型数数组的指针

int a110

int (*p)10=a;

int b10; //b=&b0 &b表示整个数组的地址了也就是行地址

p = &b;

g)一个指向函数的指针, 该函数有一个整型参数并返回一个整型数

int (*p)(int);

h)一个有10个指针的数组,该指针指向一个函数,该函数有一个整型参数并返回一个整型数

int (*a10)(int);

相关推荐
JieE2127 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
JieE2121 天前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack202 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树2 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2122 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2122 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术2 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦3 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050733 天前
(一)小红的数组操作
算法·编程语言