新手笔记-函数指针的简单应用

 将字符串赋到data中
 1
int strcpy1(char *brr, char *crr) 2 { 3 int i=0; 4 while(*(crr+i)) 5 { 6 *(brr+i) = *(crr+i); 7 i++; 8 } 9 10 *(brr+i) = '\0'; //写到了*(crr+i)造成段错误 11 } 12 13 int main() 14 { 15 int i; 16 char *arr = "hello!"; 17 char data[1024] = {0}; 18 19 int (*p)(char *, char *) = strcpy1; 20 p(data, arr); 21 22 printf("%s \n", data); 23 }

输出结果:hello!

原因:*(crr+i)在只读区,所以会段错误!

方法二:

 1 #include <stdio.h>

 2 

 3 char * strcpy1(char *brr, char *crr)

 4 {

 5         int i=0;

 6         while(*(crr+i))

 7         {

 8                 *(brr+i) = *(crr+i);

 9                 i++;

10         }

11 

12         *(brr+i) = '\0';  //写道了*(crr+i)

13         return brr;

14 }

15 

16 int main()

17 {

18         int i;

19         char *arr = "hello!";

20         char data[1024] = {0};

21 

22         char *(*p)(char *, char *) = strcpy1;

23         char *red = p(data, arr);

24 

25         printf("%s \n", red);

26 }

实现字符串的倒置:

#include <stdio.h>

#include <string.h>



char *fox(char *dest, char *src)

{

        int i, j;

        for(i=strlen(src)-1, j=0;i>=0; i--,j++)//sizeof(src)是四个字节,src是指针

        {

                *(dest+j) = *(src+i);

        }



        *(dest+j) = '\0';

        return dest;

}



int main()

{

        char *p = "hello!";



        char data[1024] = {0};



        char *(*fp)(char *, char *);

        fp = fox;

        char *red = fp(data, p);



        printf("%s \n", red);

}

注意:在fox函数中使用sizeof()返回的是指针src的大小即4字节,而不是src指向字符串的长度。

回调函数和结构体内使用函数指针:

 1 #include <stdio.h>

 2 

 3 struct person{

 4         int (*p)(int, int);

 5 };

 6 

 7 int mtod(int m, int d)

 8 {

 9         static int month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

10         int days = 0;

11         int i, j;

12 

13         if(m == 1)

14                 return d;

15         else

16         {

17                 for(i=0; i<=m-2; i++)

18                         days = days + month[i];

19                 return days+d;

20         }

21 }

22 

23 int time(int (*p)(int, int), int i, int j)

24 {

25         p(i, j);

26 }

27 

28 int main()

29 {

30         int i, j, k, l;

31         i = mtod(12,31);

32         printf("%d \n", i);

33 

34         int (*p)(int, int) = mtod;

35         j = p(1,1);

36         printf("%d \n", j);

37 

38         k = time(p, 2, 10);

39         printf("%d \n", k);

40 

41         struct person jim;

42         jim.p = mtod;

43         l = jim.p(12,30);

44         printf("%d \n", l);

45 }

今天主要内容就这些,感觉有些绕,需要更加熟练。

 

你可能感兴趣的:(函数指针)