在struct中初始化函数指针

时间:2017-09-10 06:36:11

标签: c pointers struct

typedef struct foo{
    void (*del)(void *toDel);
    char* (*p)(void *tp)
} Foo;

Foo init(char* (*print)(void*),void (*delFunc)(void*));

试图找出如何将提供的参数赋值或初始化为struct function指针。

3 个答案:

答案 0 :(得分:4)

Foo init(char* (*print)(void *toBePrinted),void (*delFunc)(void *toBeDeleted))
{
    return Foo{ .del = delFunc, .p = print};
}

这个怎么样?长篇:

Foo init(char* (*print)(void *toBePrinted),void (*delFunc)(void *toBeDeleted))
{
    Foo tmp = {
        .del = delFunc,
        .p = print
    };
    return tmp;
}

答案 1 :(得分:1)

How to initialize a struct in accordance with C programming language standards

你可以通常的方式做到:

Return (Foo){.del=delFunc, .p=print};

答案 2 :(得分:0)

foo定义为Foo并将其初始化的直接(最向后兼容的方法)是:

Foo foo = { /* Mind the order of the following initialisers!  */
  delFunc,
  print
};