How to use zero length array in C

后端 未结 4 688
天涯浪人
天涯浪人 2021-01-14 03:39

We can initialize a struct with zero length array as specified in the link:

Zero-Length.

I\'m using the following structures:

typedef unsigne         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-14 04:12

    I assume you've got some bytes in memory and you want to find the pointer to payload?

    typedef struct _CmdXHeader
    {
        UINT8 len;
        UINT8* payload;
    } CmdXhHeader;
    
    typedef struct _CommandHeader
    {
        UINT16 len;
        CmdXhHeader xhead;
    } CommandHeader;
    

    You could then cast your memory to a pointer to CommandHeader

    uint8_t* my_binary_data = { /* assume you've got some data */ };
    
    CommandHeader* cmdheader = (CommandHeader*) my_binary_data;
    
    // access the data
    cmdheader->xhead.payload[0];
    

    IMPORTANT! Unless you pack your struct, it will probably align on word boundaries and not be portable. See your compiler docs for specific syntax on how to pack the struct.

    Also, I'd only do what you've shown if you are consuming bytes (i.e. read from a file, or from a wire). IF you are the creator of the data, then I would heartily recommend against what you've shown.

提交回复
热议问题