在C中初始化函数指针

我有这个function

uint8_t Authorization_getRole (char const* userId, UsertoRole_T const *roleTable) 

在主程序中我有:

 given_Role = Authorization_getRole (userId, roleTable) 

我想用函数指针替换函数调用:

 uint8_t (*getRole_ptr)() given_Role = &getRole_ptr; 

我的问题是:

我在哪里初始化函数指针getRole_ptr?

如何初始化函数指针?

下面的语法是否正确?

 getRole_ptr = Authorization_getRole (userId, roleTable) 

我总是推荐一个带有函数指针的typedef。 然后,你会写:

 // Make sure to get the function's signature right here typedef uint8_t (*GetRole_Ptr_T)(char const*, UsertoRole_T const*); // Now initialize your pointer: GetRole_Ptr_T getRole_ptr = Authorization_getRole; // To invoke the function pointed to: given_Role = getRole_ptr(userId, roleTable); 

关于“我在哪里初始化函数指针getRole_ptr?”:取决于您的要求。 您可以在声明指针时执行此操作,就像我在示例中所做的那样,或者您可以稍后通过分配指针来更改指针:

 getRole_ptr = Some_function_with_correct_signature; 

uint8_t(* getRole_ptr)()

函数指针需要具有与指向函数完全相同的格式。 所以你需要指定两个参数的类型:

 uint8_t (*getRole_ptr)(const char*, const UsertoRole_T*); 

(否则C会把你的代码带到一个叫做隐含土地的可怕地方,那里存在像“默认参数促销”这样的怪异生物。你甚至不想知道那是什么,只需用适当的参数写出完整的函数。)

希望您可以告诉刚刚编写的函数指针声明看起来像不可读的废话。 因此,您应该使用typedef:

 typedef uint8_t (*role_ptr_t)(const char*, const UsertoRole_T*); ... role_ptr_t getRole_ptr; 

我在哪里初始化函数指针getRole_ptr? 如何初始化函数指针?

正式初始化只能在声明变量的行上进行。 因此,如果您出于某些奇怪的原因必须使用初始化而不是赋值,那么您必须在与声明相同的行上执行此操作:

  role_ptr_t getRole_ptr = Authorization_getRole; 

下面的语法是否正确?

不。请参阅上面的正确语法

您不能使用函数指针替换函数调用。 你可以改为调用指针:

 uint8_t (*getRole_ptr)(char const*, UsertoRole_T const *) given_Role = getRole_ptr( /* some args maybe */); 

初始化函数指针:

 uint8_t (*getRole_ptr)(char const*, UsertoRole_T const *) = Authorization_getRole; 

旁注:在定义函数指针时,需要指定它的参数。

通常你会定义

 uint8_t Authorization_getRole (char const* userId, UsertoRole_T const *roleTable); 

在你的标题中。

在一个代码块然后……(见评论)

 int main(int argc, const char * argv[]) { uint8_t x; // define "func" as a pointer to a function with specific arguments & return value uint8_t (*func)(char const* userId, UsertoRole_T const *roleTable); // point "func" to the function func = &Authorization_getRole; // you can use "func" as a variable or invoke it x = func( "FOO", NULL); } 

变量声明应该是:

 uint8_t(*getRole_ptr)(char const*, UsertoRole_T const *); 

你赋予它:

 getRole_ptr = Authorization_getRole; 

你用它来称呼它:

 given_Role = getRole_ptr(userId, roleTable);