【C语言】函数指针

首先看一段代码:

cpp 复制代码
#include <stdio.h>
 void test()
 {
 printf("hehe\n");
 }
 int main()
 {
 printf("%p\n", test);
 printf("%p\n", &test);
 return 0;
 }

输出的结果:

输出的是两个地址,这两个地址是 test 函数的地址。

那我们的函数的地址要想保存起来,怎么保存?

下面我们看代码:

cpp 复制代码
void test()
 {
 printf("hehe\n");
 }
 //下面pfun1和pfun2哪个有能力存放test函数的地址?
void (*pfun1)();
 void *pfun2();

首先,能给存储地址,就要求pfun1或者pfun2是指针,那哪个是指针?

答案是:

pfun1可以存放。pfun1先和*结合,说明pfun1是指针,指针指向的是一个函数,指向的函数无参 数,返回值类型为void。

练习:

cpp 复制代码
#include <stdio.h>

int Add(int x, int y)
{
	return x + y;
}

int main()
{
	int (*pAdd)(int, int) = &Add;//pAdd存放Add函数的地址

	int ret = (*pAdd)(1, 2);
	printf("%d\n", ret);

	return 0;
}

探究&Add与Add:

cpp 复制代码
#include <stdio.h>

int Add(int x, int y)
{
	return x + y;
}

int main()
{
	printf("%p\n", &Add);
	printf("%p\n", Add);

	return 0;
}

经过查阅资料得知:&Add == Add。

与数组不同:int arr\[\]; &arr != arr 。

cpp 复制代码
#include <stdio.h>

int Add(int x, int y)
{
	return x + y;
}

int main()
{
	int (*pAdd)(int, int) = Add;//也可以这样定义

	int ret1 = (*pAdd)(2, 3);
	printf("%d\n", ret1);

	int ret2 = pAdd(2, 3);
	printf("%d\n", ret2);

	int ret3 = (*****pAdd)(2, 3);
	printf("%d\n", ret3);

	return 0;
}

阅读两段有趣的代码:

cpp 复制代码
//代码1
 (*(void (*)())0)();
 //代码2
 void (*signal(int , void(*)(int)))(int);

代码2太复杂,如何简化:

cpp 复制代码
typedef void(*pfun_t)(int);
 pfun_t signal(int, pfun_t);
相关推荐
天启HTTP1 小时前
爬虫防封核心原理:IP轮换机制与风控规避逻辑
linux·服务器·网络·爬虫·tcp/ip
沐晓时光1 小时前
C语言入门,深入理解指针(3)
c语言·开发语言
信奥卷王1 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵2 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
SuperByteMaster3 小时前
wfi进入之前没有清除basepri, 导致中断优先级不够,wfi 退不出来
c语言
徐小黑ACG3 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
广州浮点FLOATLIC3 小时前
许可证服务器迁移后软件打不开:研发 IT 怎样定位连接问题
linux·服务器·数据库
Navigator_Z4 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
BLUcoding4 小时前
接口服务公网超时排查记录:SecureRandom 阻塞问题分析与解决
java·linux·springboot·aes·securerandom