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

相关推荐
晓蛋4 天前
c语言指的是什么意思
c语言·编译器·编程开发·集成开发环境·程序实例
倒头就睡的小比特4 天前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!4 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
傲世仙尊4 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
牵猫散步的鱼儿4 天前
重载、重写(覆盖)、重定义区别
c语言
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
猎头南楼4 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
phltxy4 天前
C 语言指针:从内存地址到灵活的数据访问
c语言
C语言小火车4 天前
C/C++ 为什么需要编译器?
开发语言·c++
phltxy4 天前
C 语言中的数据存储:从类型到二进制位
c语言