C language - the definition and use of function pointers and function pointers array

The method defined function pointer:

1. First, define the function type, and then define the function pointer type by

2. define the function pointer type, then define a function pointer

3. directly define the function pointer variables

#include<stdio.h>
#include<string.h>
#include"config.h"

void func()
{
	printf("hello world\n");
}

//方法1
void test01()
{
	/*
	int arr[5];
	int(ARRAY)[5];//定义数组类型
	int(*ARRAY)[5];//定义数组指针类型
	*/
	//先定义出函数类型,再通过类型定义出函数指针
	typedef void(FUNC_TYPE)();
	FUNC_TYPE* pFunc = func;

	pFunc();
}

void test02()
{
	//先定义函数指针类型,再定义函数指针
	typedef void(*FUNC_TYPE)();
	FUNC_TYPE pFunc = func;
	pFunc();
}

void test03()
{
	//直接定义函数指针变量
	void(*pFunc)() = func;
	pFunc();
}
int main()
{
	//test01();
	//test02();
	test03();
	return 0;
}

Defining and using an array of function pointers

#include<stdio.h>
#include<string.h>
#include"config.h"

void func1()
{
	printf("func1的调用\n");
}

void func2()
{
	printf("func2的调用\n");
}

void func3()
{
	printf("func3的调用\n");
}



void test03()
{
	int i;
	//函数指针数组的定义
	void(*pFunc[3])();
	pFunc[0] = func1;
	pFunc[1] = func2;
	pFunc[2] = func3;
	for(i = 0;i < 3;i++)
	{
		pFunc[i]();
	}

}
int main()
{
	//test01();
	//test02();
	test03();
	return 0;
}

 Output:

The call func1
func2 call
func3 call
, press any key to continue...

 

 

Published 67 original articles · won praise 11 · views 3910

Guess you like

Origin blog.csdn.net/weixin_42596333/article/details/104591597