I try to define function pointers as the members of the structure which can access and modify other parameters of the structure (like functions of a class in OOP).
For this, I have a structure with two function pointers:
typedef struct{
int a;
int b;
int (*init)(); // line 4
int (*multiply)(); // line 5
}STR_X2;
where the function pointers are defined as follows:
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;
}
and then I use the structure in main()
function as follows:
int main(void) {
STR_X2* val2;
val2->init = init;
val2->multiply = multiply;
val2->init(val2,7,5);
printf("result:%d\n",val2->multiply(val2));
return EXIT_SUCCESS;
}
both function pointers have one argoment of type STR_X2
. But logically I cannot define this argument because the structure STR_X2
is not defined at line 4 and 5.
My question:
Is this way of defining function pointer (without argument) safe?
Is there any better alternative to access the structure member in such function pointers?