函数指针 指针函数

趁热打铁,彻底搞一下,指针函数和函数指针;中国语言博大精深,后边是本质:

函数指针-》 是指针  

指针函数-》是函数   

int fun(int ,int) ->整形函数

int * fun(....)   ->整形指针函数

比如函数库中的strcpy(包括'\0'都要拷贝) 

char * mystrcpy(char *to, const char *from)

{

  //if(to!=NUll&&from!=NULL) 需要判空

       char *save = to;    //保存起始地址

      // for (; (*to = *from) != '/0'; ++from, ++to);写法一

      /* while(*from !='\0')写法2

    {

      *to = * from;

      to++;

      src++

     }

  */

 // while((*to++ = *from++)!='\0')//写法3

  return(save);

}

 

误区 千万不要返回局部变量的地址;

int* fun()    

{

  int i = 10;

  return &i;

} //无意义

 

 int main()

{

  char [] s1 = "hello";

  char [] s2 ;

  char * p = mystrcpy(s2,s1);

  puts(p);//hello

}

 

 

函数指针demo:

void check(char *a,char *b,int(*cmp)(constchar*,constchar*));

void main()

{

    char s1[80],s2[80];

    int(*p)(constchar*,constchar*);

    p = strcmp;                         //比较俩个串是否相等

    printf("请输入");

    gets(s1);

    gets(s2);

    check(s1, s2,p);

}

 

void check(char* a,char* b,int(*cmp)(constchar*,constchar*))   // 如果此时cmp指向的不是strcmp,而是strcpy这个时候check就拥有了拷贝字符串的功能了,这个有点像C++ 多态 ,挺奇妙的。

{

    printf("");

    if (!(*cmp)(a,b))

        printf("相等");

    else

        printf("不相等");

}

posted on 2013-11-28 01:09  大大世界  阅读(185)  评论(0编辑  收藏  举报

导航