我是 C 的新手,有 Java 背景。
如果我有一个使用来自结构定义内部函数的数据动态初始化的结构,那么这些函数何时被调用?这段代码什么时候运行?是否只是在第一次引用 sample_struct_table[i]
时?
static struct sample_struct {
int command;
int (*foo)( obj1 *banana, int num);
} sample_struct_table[] = {
{ .command = COMMAND_1,
.foo = function_name,
},
{ .command = COMMAND_2,
.foo = another_function_name,
},
};
static int function_name(obj1 *banana, int num)
{
// do stuff here
// When does this get called?
}
请您参考如下方法:
函数在您调用时被调用。在您的示例中,您所做的只是将结构的字段设置为函数指针。该函数未被调用,您只有一个指向它的指针。