Reputation: 4101
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:
functionPointer myPointer;
is incorrect)c.myPointer = foo
is incorrect)?Upvotes: 4
Views: 3532
Reputation: 755006
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.
Upvotes: 0
Reputation: 272752
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.
Upvotes: 4