4

It's pretty simple what I'm trying to do, and I'm merely having trouble figuring out the right syntax.

I want my struct to look like this:

struct myStruct
{
   functionPointer myPointer;
}

Then I have another function somewhere else that passes a function to a function and returns an instance of my struct. Here's what it does:

struct myStruct myFunction(int (*foo) (void *))
{
   myStruct c;
   c.myPointer = foo;
   return c;
}

How can I make this actually work? What's the correct syntax for:

  1. Declaring a function pointer in my struct (obviously functionPointer myPointer; is incorrect)
  2. Assigning a function's address to that function pointer (pretty sure c.myPointer = foo is incorrect)?
2

2 Answers 2

4

It's really no different to any other instance of a function pointer:

struct myStruct
{
   int (*myPointer)(void *);
};

Although often one would use a typedef to tidy this up a little.

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

Comments

0

More or less:

struct myStruct
{
    struct myStruct (*myPointer)(int (*foo)(void *));
};
typedef struct myStruct myStruct;

The c.myPointer should be fine, but you need to return a copy of the structure, not a pointer to the now vanished local variable c.

struct myStruct
{
    struct myStruct (*myPointer)(int (*foo)(void *));
};
typedef struct myStruct myStruct;

struct myStruct myFunction(int (*foo) (void *))
{
    myStruct c;
    c.myPointer = foo;
    return c;
}

This compiles but the compiler (reasonably) complains that foo is not really the correct type. So, the issue is - what is the correct type for the function pointer in the structure? And that depends on what you want it to do.

1 Comment

Your struct contains a pointer to a function returning your struct taking a pointer to another function returning an int taking a pointer to void? My head hurts.

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.