首页 > 代码库 > 函数指针的简单应用

函数指针的简单应用

 
 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指向字符串的长度。

函数指针的简单应用