【问题标题】:Initializing function pointers in struct [duplicate]在结构中初始化函数指针[重复]
【发布时间】:2018-02-18 15:31:52
【问题描述】:
typedef struct foo{
    void (*del)(void *toDel);
    char* (*p)(void *tp)
} Foo;

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

试图弄清楚如何将提供的参数分配或初始化给结构函数指针。

【问题讨论】:

    标签: c pointers struct


    【解决方案1】:

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

    你可以按照通常的方式来做:

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

    【讨论】:

    • 我需要创建一个变量类型的 Foo 吗?即 Foo foo; foo.del = delFunc
    • 什么是Return
    【解决方案2】:
    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;
    }
    

    【讨论】:

    • 你是说 .del = delFunc .p = print 吗?
    • @waffles 是的,没错,对不起
    • 这是 C99 还是 C11 标准符号?
    • @MahonriMoriancumer 是的,它是本地的,但由于函数的返回类型是Footmp 变量将被复制到调用者。例如,如果调用者执行Foo ptrs_to_fncs = init(ptr1, ptr2);,其中ptr1ptr2 是指向函数的适当指针,那么tmp 将被复制到ptrs_to_fncs,因此没有UB。在 C 中返回结构类似于在 C++ 中返回对象——它们被复制。当然,init() 函数可以重写为使用动态分配的内存。
    • @iBug 这些是指定初始化器,按照 C99 标准引入 C,但 i. e.使用 GCC,它们甚至可以在 C89 和 C++ 中用作编译器扩展(尽管可能存在一些限制)。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      • 1970-01-01
      • 2017-10-19
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多