顾名思义。
指针函数是指函数的返回值为指针类型。
函数指针是指指向函数的指针,即指针存储的是函数的首地址。
一、指针函数。
数据类型 *函数名 (参数表)
优势:能够返回一组数据,普通函数只能返回一个数据。
#include<iostream>
using namespace std;
int main()
{
char *p[5]={"Hanson","John","Tom","Joy","Monica"};
char *str=p[0];
for(int i=0;i<5;i++)
str=max(str,p[i]);
cout<<"最大的字符串是:"<<endl;
puts(str);
system("pause");
}
char *max(char *a,char *b)//char *a和char *b都是字符串(特殊的char数组),是一组数据,返回指针可以把字符串作为一组数据返回。
{
if(strcmp(a,b)>=0)
return a;
else
return b;
}
二、函数指针
数据类型 (*函数指针名)(参数表)
由于函数名是函数在内存中的首地址,因些可以直接将函数名赋值给函数指针变量。
函数指针名=函数名;
#include<iostream>
using namespace std;
void swap(int *a,int *b)
{
int temp;
temp=*a;//temp保存*a的数值
*a=*b;//将b指针所指向的变量的值,赋值给a指针所指的变量 .如果写成a=b,则意思变成把b的地址赋值给a,此时a和b同时指向原来b的地址。
*b=temp;
}
int main()
{
void (*p)(int *,int *);
p=swap;
int a=2,b=5;
(*p)(&a,&b);
cout<<a<<" "<<b<<endl;
system("pause");
}