Search code examples
carraysstructflexible-array-member

Flexible Array Member (Zero Length Array)


In reference to GCC's Zero Length Array explanation:

This is particularly useful in the case when a struct is a header for a variable-length object. This is exactly my case. Furthermore, I am concerned with the alignment of my structs in the heap.

In this case, I still really do not understand what's useful about zero length arrays. How are they related to this particular situation?

EDIT:

Is it that I can put as much "data" as I want in there?


Solution

  • Basically it allows you to have a structure with a variable length array at the end:

    struct X {
      int first;
      int rest[0];
    };
    

    An array size of 0 is not actually valid (although it is allowed as a gcc extension). Having an unspecified size is the correct way. Since C doesn't really care that you are accessing elements beyond the end of the array, you just start with an undefined array size, and then allocate enough memory to handle however many elements you actually want:

    struct X *xp = (struct X *)malloc(sizeof(struct X)+10*sizeof(int));
    xp->rest[9] = 0;