C程序中函数指针

本文深入探讨了C语言中函数指针的概念、声明方法、使用场景及实例演示,包括如何通过函数指针调用函数和作为参数传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<style type="text/css"> <!-- p {margin-bottom:0.21cm} --> </style>

C程序在编译时,每一个函数都有一个入口地址,该地址就是函数指针所指向的地址。有了指向函数的指针变量后,可用该指针变量调用函数,就如同用指针变量可引用其他类型变量一样,其概念上是一致的。函数指针有两个用途:调用函数和做函数的参数。


函数指针的声明方法如下:

函数类型(标志符 指针变量名)(形参列表)

注:

1)“函数类型”:说明该函数的返回类型;

2)“(标志符 指针变量名)”:该括号不能省略,说明了一个返回的数据类型是指针的函数

3)“形参列表”:表示指针变量指向的函数所带的参数列表。


举例:

int func(int x , int y) //声明一个函数

int (*f)(int x, int y) //声明一个函数指针

f = func; //将func函数的首地址赋给指针f;

赋值时函数func不带括号,也不带参数,由于func代表函数的首地址,因此经过赋值以后,指针f就指向函数func(int x, int y)的代码的首地址。

测试代码如下:

#include <stdio.h>
void test(char *str)
{
	printf("%s\n", str);
}

int main()
{
	void (*t)(char*);

	char *s = "This is a test!\n";

	t = test;
	(*t)(s);

	return 0;
}

有些编译器可能编译不通过,需要改为如下的形式:

#include <stdio.h>

typedef void (*t_ptr)(char*);

void test(char *str)
{
	printf("%s\n", str);
}

int main()
{
//	void (*t)(char*);

	char *s = "This is a test!\n";

	t_ptr t = test;
	t(s);

	return 0;
}

另一个函数指针数组的例如:

#include <stdio.h>

typedef void (*init_func)(void);

void hello1(void)
{
	printf("hello 1\n");
}

void hello2(void)
{
	printf("hello 2\n");
}

void hello3(void)
{
	printf("hello 3\n");
}

static init_func init[] = {
	hello1,
	hello2,
	hello3,
	0,
};

int main()
{
	int i;
	for(i = 0; init[i]; i++)
	{
		init[i]();
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值