user2709168
user2709168

Reputation: 117

Initializing a struct containing function pointers in C

The struct boxis defined in box.h as such:

typedef struct box {
    int (*func1) (const void *p1, const void *p2);
    void (*func2) (void *p3);
} Box;

box.c includes box.h and has the following function:

int create_box(int (*func1)(const void *p1, const void *p2), void (*func2)(const void *p3), Box **box) {

create_box is called to initialize a box based on the provided parameters. I'm struggling to figure out how to assign the provided function pointers to the fields of the structure. First, I start out by allocating memory to **box via (*box) = malloc(sizeof(Box));

But then I try to assign the arguments of the function pointer through

(*box)->func1 = (func1)(&p1, &p2);
(*box)->func2 = (func2)(&p3);

Running this tells me that all of my pointers are undeclared. Clearly there's something I'm misunderstanding about how function pointers work, but I don't understand how I'm supposed to initialize them (if that's the write word). I've tried replacing the right side with (*func1)(*p1, *p2), (func1)(p1, p2), (*func1)(p1, p2), (*func1)(&p1, &p2), etc. but they haven't yielded anything that I can understand. How do I properly initialize this structure's function pointers?

I'm working in C90 if that's relevant.

Upvotes: 0

Views: 796

Answers (1)

bruno
bruno

Reputation: 32586

if I well understand

(*box)->func1 = (func1)(&p1, &p2);
(*box)->func2 = (func2)(&p3);

is in int create_box(int (*func1)(const void *p1, const void *p2), void (*func2)(const void *p3), Box **box) { so you wanted :

(*box)->func1 = func1;
(*box)->func2 = func2;

The form (func1)(&p1, &p2); calls the function whose address is in func1 with the address of p1 and p2 in argument (the "()" around func1 is useless) and this is visibly not what you want and can do because p1 and p2 are not defined.

But (*box)->func2 = func2; is not possible with your current code because the signature of (*box)->func2 and func2 do not correspond. You can change the second argument of create_box to be void (*func2)( void *p3) or to modify the struct box to have void (*func2) (const void *);

Upvotes: 6

Related Questions