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)?
Casey Patton
  • 4,021
  • 9
  • 41
  • 54
  • If you return a myStruct *, you should allocate (eg, use malloc) and return the malloced value. If you return a myStruct, you should declare your function as such. (Right now, you declare that the function returns a pointer, but you attempt to return a struct.) – William Pursell Jan 14 '12 at 02:14
  • possible duplicate of [Function Pointer in C](http://stackoverflow.com/questions/1278841/). See also [Function pointer as a member of a C struct](http://stackoverflow.com/questions/1350376/), [Struct with pointer to a function](http://stackoverflow.com/questions/2939003/), [typedef is your friend](http://stackoverflow.com/a/8028634/90527). – outis Jan 14 '12 at 02:19

2 Answers2

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    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. – Dave Jan 14 '12 at 05:03