简体   繁体   中英

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

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();
#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM