使用函数指针实现字符串的追加与字符串的拷贝功能
mystrcat.c
#include <stdio.h>
char *mystrcat(char *dest, const char *src)
{
char *tmp = dest;
while(*dest !='\0')
{
dest++;
}
while(*src != '\0')
{
*dest = *src;
dest++;
src++;
}
*dest = '\0';
return tmp;
}
mystrcpy.c
#include <stdio.h>
char *mystrcpy(char *dest, const char *src)
{
char *tmp = dest;
while(*src != '\0')
{
*tmp = *src;
tmp++;
src++;
}
*tmp = '\0';
return dest;
}
main.c
#include <stdio.h>
typedef char* (*pfunc_t)(char *,const char *);
char *mystrcat(char *,const char *);
char *mystrcpy(char *,const char *);
char *str_func(char *dest,const char *src,pfunc_t pfunc)
{
return (*pfunc)(dest,src);
}
int main(int argc, const char *argv[])
{
char buf[32] = "hello ";
char *p = "world";
printf("%s\n",str_func(buf,p,mystrcat));
printf("%s\n",str_func(buf,p,mystrcpy));
return 0;
}
测试