如何在 C 的联合中获取结构的大小?

How to get the size of a struct within a union in C?

如何在 C 语言的联合中获取结构的大小?

给定以下定义:

typedef union
{
    struct req_
    {
        uint8_t cmd1;
        uint8_t cmd2;
    } req;

    struct rsp_
    {
        uint8_t cmd_result;
        uint8_t status_1;
        uint8_t status_2;
        uint8_t status_3;
        uint8_t status_4;
    } rsp;
} msg_t;

sizeof(msg_t) 将提供并集的最大大小,在本例中为 5,因为 rsp_ 大于 req_

如何获得sizeof(req_)

像这样:

sizeof(struct req_);

例如:

int main()
{
    printf("sizeof msg_t=%zd\n",sizeof(msg_t));
    printf("sizeof struct req_=%zd\n",sizeof(struct req_));
}

输出:

sizeof msg_t=5
sizeof struct req_=2

req_ 是一个结构标签。您需要将 struct

size_t size = sizeof(struct req_);

或使用声明的结构变量

size_t size = sizeof(msg_t.req_.req);