Linux/C 高级——函数指针

1.概念

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

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

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

int a[2][3];

int (*p)[3] = a;

//p[i][j] *(p[i]+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 (*arr[3])(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 (*arr[2])(int, int) = {add, sub}; //函数指针数组

printf("%d %d\n", arr[0](1, 2), arr[1](3, 4));

return 0;

}
练习:
a) 一个整型数

int a;

b) 一个指向整型的指针

int *p=&a;

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

int **q=&p;

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

int arr[10];

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

int *a[10];

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

int a[1][10]

int (*p)[10]=a;

int b[10]; //b=&b[0] &b表示整个数组的地址了也就是行地址

p = &b;

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

int (*p)(int);

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

int (*a[10])(int);

相关推荐
qq_49244844628 分钟前
Jmeter设置负载阶梯式压测场景(详解教程)
开发语言·python·jmeter
ID_180079054731 小时前
京东获取整站实时商品详情数据|商品标题|数据分析提取教程
java·开发语言
StarPrayers.2 小时前
旅行商问题(TSP)(2)(heuristics.py)(TSP 的两种贪心启发式算法实现)
前端·人工智能·python·算法·pycharm·启发式算法
qiuiuiu4132 小时前
正点原子RK3568学习日志-编译第一个驱动程序helloworld
linux·c语言·开发语言·单片机
爱吃橘的橘猫2 小时前
嵌入式系统与嵌入式 C 语言(2)
c语言·算法·嵌入式
235162 小时前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
molong9312 小时前
Kotlin 内联函数、高阶函数、扩展函数
android·开发语言·kotlin
盼哥PyAI实验室2 小时前
踏上编程征程,与 Python 共舞
开发语言·python
阿无,3 小时前
Java设计模式之工厂模式
java·开发语言·设计模式
weixin_307779133 小时前
使用Python高效读取ZIP压缩文件中的UTF-8 JSON数据到Pandas和PySpark DataFrame
开发语言·python·算法·自动化·json