【C++札记】指针函数与函数指针

指针函数

指针函数是一个函数,只不过指针函数返回的类型是某一类型的指针。

格式:

类型名* 函数名(函数参数列表)

如下代码存在问题

void test(char *p)
{
	p = (char*)malloc(10);
	return;
}

int main()
{
	char* p1 = NULL;

	test(p1);
	return 1;
}

test函数执行完后,p1仍为NULL,调用test函数,实参p1为值传递,即使函数内申请的内存,函数外不会得到,可以使用函数指针的形式进行修改,如下:

char* test()
{
	char* p = (char*)malloc(10);
	memset(p, 0, 10);
	return p;
}

int main()
{
	char* p1 = NULL;

	p1 = test();
	return 1;
}

函数指针

函数指针是指向函数的指针变量。所以函数指针其实是指针变量,只不过该指针变量指向函数。

格式:

类型名 (*指针变量名) (函数参数列表)

函数指针的用途:

a.调用函数
b.做函数的参数.

调用函数使用:

/*
*	函数指针,调用函数
*/

int fun1(int a, int b)
{
	return a + b;
}

typedef int(FUNC*)(int a,int b)

int main()
{
//方式一
	int(*p)(int, int);
	p = fun1;
	printf("%d
", p(1, 5));
//方式二
    FUNC f = fun1;
    printf("%d
", f(1,5));
	getchar();
	return 1;
}

函数参数使用:

/*
*	函数指针,最为参数
*/

int fun2(int a, int b)
{
	return a + b;
}

int fun3(int a, int b, int(*f)(int, int))
{
	return f(a, b);
}

int main()
{
	printf("%d
", fun3(1, 5, fun2));
	getchar();
	return 1;
}

欢迎加群交流:C/C++开发交流

原文地址:https://www.cnblogs.com/woniu201/p/11694588.html