How to use zero length array in C

后端 未结 4 685
天涯浪人
天涯浪人 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:08

    A zero-length array at the end of a struct, or anywhere else, is actually illegal (more precisely a constraint violation) in standard C. It's a gcc-specific extension.

    It's one of several forms of the "struct hack". A slightly more portable way to do it is to define an array of length 1 rather than 0.

    Dennis Ritchie, creator of the C language, has called it "unwarranted chumminess with the C implementation".

    The 1999 revision of the ISO C Standard introduced a feature called the "flexible array member", a more robust way to do this. Most modern C compilers support this feature (I suspect Microsoft's compiler doesn't, though).

    This is discussed at length in question 2.6 of the comp.lang.c FAQ.

    As for how you access it, whichever form you use, you can treat it like you'd treat any array. The name of the member decays to a pointer in most contexts, allowing you to index into it. As long as you've allocated enough memory, you can do things like:

    CommandHeader *ch;
    ch = malloc(computed_size);
    if (ch == NULL) { /* allocation failed, bail out */ }
    ch.len = 42;
    ch.payload[0] = 10;
    ch.payload[1] = 20;
    /* ... */
    

    Obviously this is only a rough outline.

    Note that sizeof, when applied to the type CommandHeader or an object of that type, will give you a result that does not include the flexible array member.

    Note also that identifiers starting with underscores are reserved to the implementation. You should never define such identifiers in your own code. There's no need to use distinct identifiers for the typedef name and the struct tag:

    typedef struct CommandHeader
    {
        UINT16 len;
        UINT8 payload[0];
    } CommandHeader;
    

    I'd also suggest using the standard types uint16_t and uint8_t, defined in (assuming your compiler supports it; it's also new in C99).

    (Actually the rules for identifiers starting with underscores are slightly more complex. Quoting N1570, the latest draft of the standard, section 7.1.3:

    • All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
    • All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.

    And there are several more classes of reserved identifiers.

    But rather than working out which identifiers are safe to use at file scope and which are safe to use in other scopes, it's much easier just to avoid defining any identifiers that start with an underscore.)

提交回复
热议问题