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);

相关推荐
小羊在睡觉16 分钟前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
3DVisionary30 分钟前
蓝光三维扫描:医疗制造的精度焦虑怎么解
人工智能·算法·制造·蓝光三维扫描·医疗制造·三维检测·义齿检测
AI玫瑰助手36 分钟前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
好评笔记39 分钟前
机器学习面试八股——常用损失函数
人工智能·深度学习·算法·机器学习·校招
weixin_4684668540 分钟前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
油炸自行车1 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋1 小时前
C++14特性
开发语言·c++·c++14特性
_日拱一卒1 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
珂朵莉MM2 小时前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第3赛季优化题--束搜索
人工智能·算法
Omics Pro2 小时前
首个!外源天然产物综合性代谢图谱
数据库·人工智能·算法·机器学习·r语言