结构体嵌套及定义方式

1,结构体定义一

定义:

typedef struct

{

    GPIO_TypeDef* port_x;    //引脚组

    uint32_t gpio_x;        //引脚号

}gpio_struct;

 

typedef struct

{

    gpio_struct sda;         //成员变量会有内存分配 

    gpio_struct scl;

    uint16_t data;

}nixie_tube_struct;

 

申明结构体变量:

nixie_tube_struct nixie_tube_handler = {0};

 

成员变量初始化:

nixie_tube_handler.sda.port_x = GPIO2;

nixie_tube_handler.sda.gpio_x = GPIO_Pin_3;

 

nixie_tube_handler.scl.port_x = GPIO2;

nixie_tube_handler.scl.gpio_x = GPIO_Pin_2;

 

2,结构体定义二

typedef struct

{

    GPIO_TypeDef* port_x;    //引脚组

uint32_t gpio_x;        //引脚号

}gpio_struct;

 

typedef struct

{

    gpio_struct* sda;        //指针变量,需要手动分配空间   

    gpio_struct* scl;

    uint16_t data;

}nixie_tube_struct;

申明结构体变量:

nixie_tube_struct nixie_tube_handler = {0};

 

成员变量初始化:

//结构体指针所指向的结构体,需要分配空间

nixie_tube_handler.sda = (gpio_struct*)malloc(sizeof(gpio_struct));

nixie_tube_handler.scl = (gpio_struct*)malloc(sizeof(gpio_struct));

        

nixie_tube_handler.sda->port_x = GPIO2;

nixie_tube_handler.sda->gpio_x = GPIO_Pin_3;

 

nixie_tube_handler.scl->port_x = GPIO2;

nixie_tube_handler.scl->gpio_x = GPIO_Pin_2;

 

结构体中的指针成员变量所指向的结构体需要分配地址及空间,指针只是个地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章