在C中初始化函数指针

use*_*679 5 c pointers function-pointers function

我有这个功能

uint8_t Authorization_getRole (char const* userId, UsertoRole_T const *roleTable)
Run Code Online (Sandbox Code Playgroud)

在我的主程序中:

given_Role = Authorization_getRole (userId, roleTable)
Run Code Online (Sandbox Code Playgroud)

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

uint8_t (*getRole_ptr)()

given_Role = &getRole_ptr;
Run Code Online (Sandbox Code Playgroud)

我的问题是:

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

如何初始化函数指针?

下面的语法是否正确?

getRole_ptr = Authorization_getRole (userId, roleTable)
Run Code Online (Sandbox Code Playgroud)

let*_*tar 5

我总是推荐一个带有函数指针的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);
Run Code Online (Sandbox Code Playgroud)

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

getRole_ptr = Some_function_with_correct_signature;
Run Code Online (Sandbox Code Playgroud)