函数指针

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct STTest
{
	int cmd;
	void (*PTRFUN)(void); 
}sttest;

void func1(void)
{
	printf("func1\n");
}

void func2(void)
{
	printf("func2\n");
}

const sttest arr[] = 
{
	{1, func1},
	{2, func2},
};

int main()
{
	for(int i=0; i<=1; i++)
	{
		printf(" --- %d --- \n", arr[i].cmd);
		arr[i].PTRFUN();
	}
}
结果:
 --- 1 --- 
func1
 --- 2 --- 
func2
#include <stdio.h>

void F_onefunc(int num)
{
	printf("F_onefunc %d\n", num);
}

void F_twofunc(int num1, int num2)
{
	printf("F_twofunc %d %d \n", num1, num2);
}

void F_threefunc(void)
{
	printf("F_threefunc\n");
}

struct textattr
{
	void(*onefunc)(int);
	void(*twofunc)(int, int);
	void(*three)(void);
};

const struct textattr funtmp = {F_onefunc, F_twofunc, F_threefunc};

int main()
{
	printf("%d \n", sizeof(funtmp));
	const struct textattr *pfuntmp[] = {&funtmp,};
	int num = (int) (sizeof(pfuntmp) / sizeof(pfuntmp[0]));
	printf("sizeof num %d\n", num);
	pfuntmp[0]->onefunc(9);
	pfuntmp[0]->twofunc(8,9);
	pfuntmp[0]->three();
}

指针数组:array of pointers,即用于存储指针的数组,也就是数组元素都是指针

数组指针:a pointer to an array,即指向数组的指针

还要注意的是他们用法的区别,下面举例说明。

int* a[4] 指针数组

             表示:数组a中的元素都为int型指针    

             元素表示:*a[i]   *(a[i])是一样的,因为[]优先级高于*

int (*a)[4] 数组指针

             表示:指向数组a的指针

             元素表示:(*a)[i]  

注意:在实际应用中,对于指针数组,我们经常这样使用:

typedef int* pInt;
pInt a[4];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值