0

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_X2is 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?

Behy
  • 483
  • 7
  • 23
  • 2
    If you give the struct a name `typedef struct name {` you can use `struct name*` in the declarations inside the struct. (Not that I see the advantage of writing `val2->multiply(val2)` instead of just `multiply(val2)`, but perhaps that's just me). – Bo Persson Sep 07 '17 at 14:28
  • For true OOP, you might want to look into opaque type/opaque pointers: https://stackoverflow.com/a/13032531/584518 – Lundin Sep 07 '17 at 15:00

1 Answers1

1

Basically what you want here is a forward declaration of a structure type. You can achieve this by using structure tags. For example:

typedef struct STR_X2_S STR_X2;

struct STR_X2_S {
    int a;
    int b;
    int (*init)(STR_X2 *self, int _a, int _b);
    int (*multiply)(STR_X2 *self);
};
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41