Casey Patton
Casey Patton

Reputation: 4101

How to use function pointers in a struct in C?

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)?

Upvotes: 4

Views: 3532

Answers (2)

Jonathan Leffler
Jonathan Leffler

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

Oliver Charlesworth
Oliver Charlesworth

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

Related Questions