【发布时间】: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*));
试图弄清楚如何将提供的参数分配或初始化给结构函数指针。
【问题讨论】:
typedef struct foo{
void (*del)(void *toDel);
char* (*p)(void *tp)
} Foo;
Foo init(char* (*print)(void*),void (*delFunc)(void*));
试图弄清楚如何将提供的参数分配或初始化给结构函数指针。
【问题讨论】:
How to initialize a struct in accordance with C programming language standards
你可以按照通常的方式来做:
Return (Foo){.del=delFunc, .p=print};
【讨论】:
Return?
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;
}
【讨论】:
Foo,tmp 变量将被复制到调用者。例如,如果调用者执行Foo ptrs_to_fncs = init(ptr1, ptr2);,其中ptr1 和ptr2 是指向函数的适当指针,那么tmp 将被复制到ptrs_to_fncs,因此没有UB。在 C 中返回结构类似于在 C++ 中返回对象——它们被复制。当然,init() 函数可以重写为使用动态分配的内存。
将foo 定义为Foo 并对其进行初始化的直接(最向后兼容的方法)是:
Foo foo = { /* Mind the order of the following initialisers! */
delFunc,
print
};
【讨论】: