0

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.

2
  • 1
    Maybe (*box)->func1 = func1;? Commented May 2, 2019 at 15:54
  • note that p1 and p2 in type declaration are not needed. I mean int (*func1)(const void*p1, const void *p2) means the same as int (*func1)(const void*, const void *). Commented May 2, 2019 at 16:14

1 Answer 1

6

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 *);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.