指针函数、函数指针、指针数组、数组指针

1、函数指针
(1) float(**def)[10]:def是一个二级指针,它指向的是一个一维数组指针,数组的元素都为float;
(2) double*(*gh)[10]:gh是一个指针,它指向一个一维数组,数组元素都是double*。
(3) double(*f[10])():f是一个数组,f有10个元素,元素都是函数指针,指向的函数类型是没有参数且返回double的函数。
(4) int*((*b)[10]):等同于int* (*b)[10],b是一维数组的指针。
(5) Long(*fun)(int):函数指针
(6) int(*(*F)(int,int))(int):F是一个函数指针,指向的函数的类型是有两个int参数并且返回一个函数指针的函数,返回的函数指针指向有一个int参数且返回int的函数。

//指针函数
char *p(char *s1,char *s2)
{
    char *s;
    while(true)
    {
        if(*s1!=*s2)
        {
            s1++;s2++;
        }
        else
        {
            s=s1;
            break;
        }
    }
    return s;
}
int main()
{
    char *s1="aaabbbcccefgg";
    char *s2="kkkkkkcckk";
    cout<<p(s1,s2)<<endl;//cccefgg
    return 0;
}

 

//函数指针
//情况1 ---> 返回类型(*函数名)(参数表)
int (*FUN1)(int,int);
int pfun1(int a,int b)
{
    return a>b? a:b;
}

//情况2 ---> typedef 返回类型(*新类型)(参数表)
typedef char(*FUN2)(int);
FUN2 pfun2;
char fun2(int a)
{
    char c='a';
    c+=a;
    return c;
}int main()
{
    FUN1=pfun1;
    cout<<(*FUN1)(10,20)<<endl;//20

    pfun2=fun2;
    cout<<(*pfun2)(2)<<endl;//c

    return 0;
}

 //情况3 ---> 函数指针与typedef

2、指针操作数组

int a[5]={1,2,3,4,5};
int *p;

p=a+1;
cout<<*p<<endl;//2
p=p+1;
cout<<*p<<endl;//3
p++;
cout<<*p<<endl;//4

3、指针数组和数组指针
int(*p)[]:指向数组的指针,即数组指针
int*p[]:指针数组,里面存的是地址,它指向位置的值为*p[0],*p[1].....
int*(p[]):指针数组,同上
int p[]:普通指针
(1)指针数组:

 

    char *a[2]={"abcd","1234"};//指针数组,数组中含有两个指针分别指向数组中的字符串
    cout<<*a[0]<<'\t'<<*a[1]<<endl;//a  1
    *a[0]++;*a[1]++;
    cout<<*a[0]<<'\t'<<*a[1]<<endl;//b  2

 

(2)数组指针

 

    int arr[10]={1,2,3,4,5,6,7,8,9,10};
    int *p1 = arr;//一维数组指针
    int *p2 = (int*)&arr;//一维数组指针
    int (*p3)[10] = &arr;//定义一个指针,指向该数组 *p3==a
    cout<<arr<<'\t'<<p1<<'\t'<<p2<<'\t'<<*p3<<endl;//0x7ffee759ccb0  0x7ffee759ccb0  0x7ffee759ccb0  0x7ffee759ccb0
    p1++;p2++;
    cout<<*p1<<'\t'<<*p2<<'\t'<<(*p3)[0]<<'\t'<<(*p3)[1]<<endl;//2  2  1  2
    int *p4=(*p3);
    cout<<*p4<<endl;//1
    ++p4;
    cout<<*p4<<endl;//2

 

posted @ 2018-07-04 20:04  ybf&yyj  阅读(1081)  评论(0编辑  收藏  举报