简体   繁体   中英

initialize and apply structure-parameters using function pointers as structure members

In the following code:

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int a;
    int b;
    int (*func1)();
    int (*func2)();
}STR_X2;
void init(STR_X2 self , int _a , int _b){
    self.a = _a;
    self.b = _b;
    printf("Init a:%d, b:%d \n",self.a,self.b);
}
int multiply(STR_X2 self){
    printf("Multiply a:%d, b:%d, res:%d\n",self.a,self.b,self.a*self.b);
    return self.a*self.b;
}

int main(void) {
    static STR_X2 val2;
    val2.func1 = init;
    val2.func2 = multiply;

    printf("set values of a and b using init() function\n");
    val2.func1(val2,3,5);
    printf("result:%d\n",val2.func2(val2));

    printf("\nset values of a and b directly\n");
    val2.a=3;
    val2.b = 5;
    printf("result:%d\n",val2.func2(val2));
    return EXIT_SUCCESS;
}

the structure STR_X2 has two members as function pointers.

  • func1 is set as init() and ses values of the Parameters a and b .
  • func2 is set as multiply() and multiplies the a and b

By running the code, I have the following result:

set values of a and b using init() function
Init a:3, b:5 
Multiply a:0, b:0, res:0
result:0

set values of a and b directly
Multiply a:3, b:5, res:15
result:15

which means initializing the parameters using func1() does not work.
Could anybody help me to find what's wrong with this code?
Thanks

You're taking STR_X2 by value in init and multiply - this causes a copy. Take it by pointer instead to modify the static instance you declared in main .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM