简体   繁体   English

如何在结构中存储函数指针?

[英]How can I store a function pointer in a structure?

I have declared typedef void (*DoRunTimeChecks)(); 我声明了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()? 我如何调用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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