示例代码及注释:
#include
typedef struct
{
void (*pCallback) (int a, int b); //函数指针
int a;
} CM_HANDLERS_T;
/* 定义函数handle */
void handle (int a , int b)
{
printf("%d %d", a, b);
}
/* 声明CM_HANDLERS_T类型的结构体变量,同时赋初值 */
#if 0
/* 方法一 初始化时直接按定义结构体的数据类型的顺序赋值 */
static CM_HANDLERS_T g_hanlder = {&handle,
5};
#endif
/* 方法四 初始化时指定数据类型赋值 */
static CM_HANDLERS_T g_hanlder = {.pCallback = &handle,
.a = 5}; //用{}和.的形式在声明的时候初始化变量
int main(void)
{
/* 方法二 定义结构体变量后逐一赋值 */
#if 0
CM_HANDLERS_T g_hanlder;
g_hanlder.pCallback = &handle;
g_hanlder.a = 5;
#endif
/* 方法三 定义结构体变量,再一次性赋值 */
#if 0
CM_HANDLERS_T g_hanlder;
g_hanlder = (CM_HANDLERS_T){&handle,5};
#endif
printf("%p %p",g_hanlder.pCallback,handle);
return 0;
}
输出结果:
Note:
函数的地址: handle与&handle一样,为了形象的表示函数地址,所以用了取地址的符号&,从上述结果可以看出:赋值时候用了取址符号,printf时候未使用取址符号,输出的结果是相同的。