Mawg
Mawg

Reputation: 40150

How can I store a function pointer in a structure?

I have declared typedef void (*DoRunTimeChecks)();

How do I store that as a field in a struct? How do I assign it? How do I call the fn()?

Upvotes: 16

Views: 15528

Answers (2)

majie
majie

Reputation: 1529

#include <stdio.h>

typedef void (*DoRunTimeChecks)();

struct func_struct {
    DoRunTimeChecks func;
};

void function()
{
    puts("hello");
}

int main()
{
    struct func_struct func_struct;
    func_struct.func = function;
    func_struct.func();
    return 0;
}

Upvotes: 6

Carl Norum
Carl Norum

Reputation: 224944

Just put it in like you would any other field:

struct example {
   int x;
   DoRunTimeChecks y;
};

void Function(void)
{
}

struct example anExample = { 12, Function };

To assign to the field:

anExample.y = Function;

To call the function:

anExample.y();

Upvotes: 21

Related Questions