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

相关推荐
bbq粉刷匠12 分钟前
HashMap 底层原理深度拆解(二):putVal 完整链路解析(懒加载 · 链表遍历 · 尾插法)
java·开发语言·哈希算法
影视飓风TIM27 分钟前
Linux下C语言缓冲区原理 + Git版本控制
linux·c语言·git
jarvisuni31 分钟前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
@三十一Y33 分钟前
C++:红黑树的实现
开发语言·c++
kobesdu42 分钟前
流形上的优化:SO(3)与SE(3)的广义加减法在FAST-LIO中如何简化状态估计
人工智能·算法·fastlio
白狐_7981 小时前
408 数据结构算法题 01:线性表暴力求解保分指南
java·数据结构·算法
乐观勇敢坚强的老彭1 小时前
C++信奥:开关门、开关灯问题
开发语言·c++·算法
冻柠檬飞冰走茶1 小时前
PTA基础编程题目集 7-31 字符串循环左移(C语言实现)
c语言·开发语言·数据结构·算法
Hi李耶2 小时前
【LeetCode】4-寻找两个正序数组的中位数
算法·leetcode·职场和发展
图灵机z2 小时前
【算法提高课】AcWing 1027. 方格取数 长期攻克提高课-day3(3/219)
算法