指针作为函数参数/指针类型的函数/指向函数的指针(function pointer)

指针作为函数参数:

为什么需要指针做参数: 1. 需要数据双向传递时(引用也可以达到此效果)

                                     2. 需要传递一组数据,只传首地址运行效率比较高

example:

#include <iostream>
using namespace std;


const int N = 6;

void print(const int *p, int n); //这里const是为了防止 通过指针改变了指针指向的值,代表指针指向的是一个常量

int mai(){
	int array[N];
	for (int i =0; i<N; i++)
		cin>>array[i];
	print(array, N);
	return 0;
}
void print(const int *p, int n){
	cout<<"{" <<*p;
	for (int i =1; i<n; i++)
		cout <<"," << *(p+1);
	cout <<"}"<<endl;
}

指针类型的函数:

语法形式:

存储类型 数据类型 *函数名()

{ //函数主题

}


注意事项:不要将非静态局部地址用作函数的返回值//这代表这个地址是非法地址,因为有可能在调用函数中得到的地址是一个已经无效的地址

                 返回的指针要确保在主调函数中是有效,合法的地址

                  在子函数中通过动态内存分配new操作取得的内存地址返回给主函数是合法有效的。但是内存分配和释放不在同一级别,要注意不要忘记释放,避免内存泄漏。



指向函数的指针: 

指针里面容纳的是函数代码的首地址

函数指针的定义:

定义形式:

存储类型 数据类型(*函数指针名)();//注意第一个括号,如果没有这个括号则为指针类型的函数

例子:int (*p) (int i, int j);

含义:

函数指针指向的是程序代码存储区

目的:

执行函数回调  :将指针作为函数的形参

例子:

#include <iostream>
using namespace std;


int compute(int a, int b, int(*func)(int, int)){  // 这里定义名为func的指针 作为形参
	return dunc(a,b);

}

int max(int a, int b){
	return ((a > b )? a:b);

}

int max(int a, int b){
	return ((a < b )? a:b);

}

int max(int a, int b){
	return (a+b);

}

int main(){
	int a, b, res;
	cout <<"Please insert an integer a: "; cin >>a;
	cout<<"Please insert an integer b: "; cin >> b;


	res = compute(a,b, & max); //& max 代表对max函数取址
	cout<<"Max of" << a << " and " << b << " is " << res <<endl;
	res = compute(a,b, & min); //& max 代表对max函数取址
	cout<<"Min of" << a << " and " << b << " is " << res <<endl;
	res = compute(a,b, & sum); //& max 代表对max函数取址
	cout<<"Sum of" << a << " and " << b << " is " << res <<endl;
}




猜你喜欢

转载自blog.csdn.net/weixin_42380877/article/details/80937452