结构体变量的初始化的四种形式,其中第四种形式是写本次博客目的,暂且mark一下。
示例代码及注释
#include <stdio.h>
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;
}