天热无聊,用C语言函数指针实现的小函数^_^
#include <stdio.h> #include <string.h> #include <stdlib.h> void f_sum(double* ,double*,double*); void i_sum(int *,int *,int *); void c_sum(char*,char*,char*); int main(int argc,char **argv) { int a=10; int b=5; double c=2.3; double d=2.2; double fs; int is; char *ca="Hello "; char *cb="World!"; char *cs; void *res=0; void (*pfunc) (void*,void*,void*); pfunc=f_sum; pfunc(&c,&d,&fs); res=&fs; printf("float:result=%.2f\n",*(double*)res); pfunc=i_sum; pfunc(&a,&b,&is); printf("int:result=%2d\n",is); pfunc=c_sum; cs=malloc(strlen(ca)+strlen(cb)+1); memset(cs,0x00,strlen(ca)+strlen(cb)+1); pfunc(ca,cb,cs); printf("char:result=%s\n",cs);
free(cs); return 0; } void f_sum(double *x,double *y,double *z) { *z=(*x)+(*y); } void i_sum(int *x,int *y,int *z) { *z=(*x)+(*y); } void c_sum(char *x,char *y,char *z) { //memset(z,0x00,strlen(x)+strlen(y)); sprintf(z,"%s%s",x,y); }