Function pointer to different functions with different arguments in C

前端 未结 6 1073
独厮守ぢ
独厮守ぢ 2020-12-31 08:48

I have two functions with variable number and types of arguments

double my_func_one(double x, double a, double b, double c) { return x + a + b + c }
double my         


        
6条回答
  •  佛祖请我去吃肉
    2020-12-31 09:08

    A sample of Typecasting approach for using a same function pointer for different functions of different prototypes. <>

    #include 
    typedef void (*myFuncPtrType) (void);
    
    typedef int (*myFunc2PtrType)(int, int);
    
    typedef int * (*myFunc3PtrType)(int *);
    
    static void myFunc_1 (void);
    static int myFunc_2 (int, int);
    static int* myFunc_3 (int *);
    
    const myFuncPtrType myFuncPtrA[] = {
                                        (myFuncPtrType)myFunc_1,
                                        (myFuncPtrType)myFunc_2,
                                        (myFuncPtrType)myFunc_3
    };
    
    static void myFunc_1 (void)
    {
        printf("I am in myFunc_1 \n");
    }
    
    static int myFunc_2 (int a, int b)
    {
        printf("I am in myFunc_2\n");
        return (a+b);
    }
    
    static int* myFunc_3 (int *ptr)
    {
        printf("I am in myFunc_3\n");
        *ptr = ((*ptr) * 2);
        return (ptr+1);
    }
    
    int main(void) {
        // your code goes here
        int A[2],C;
    
        int* PTR = A;
    
        (*(myFuncPtrA[0]))();
    
        A[0]=5;
        A[1]=6;
    
        C = ((myFunc2PtrType)(*(myFuncPtrA[1])))(A[0],A[1]);
    
        printf("Value of C: %d \n", C);
    
        printf("Value of PTR before myFunc_3: %p \n", PTR);
        printf("Value of *PTR before myFunc_3: %d \n", *PTR);
    
        PTR = ((myFunc3PtrType)(*(myFuncPtrA[2])))(&A);
    
        //Lets look how PTR has changed after the myFunc_3 call
    
        printf("Value of PTR after myFunc_3: %p \n", PTR);
        printf("Value of *PTR after myFunc_3: %d \n", *PTR);
    
    
        return 0;
    }
    

提交回复
热议问题