Zero-length arrays

Earlier this morning, my classmate and friend Raj (who btw is a hardcore open-source gnu/linux guy) sent an email to our class mailing list commenting on how he found a struct in some code he was working on that had a zero-length array member, and how he thought that was weird. What he was talking about was the old C-style flexible arrays, where you could legally define a zero-length array as the last member of a struct definition. The idea is to use this zero-length array as a reference to variable length data that’d be stored using the struct. If you are wondering why a pointer is not used, the size of a pointer would be non-zero, whereas the size of a zero-length array is guaranteed to be zero.

The GNU C compiler apparently still permits this, and the VC++ 2005 compiler permits it too, though it issues a Level-4 warning if it’s C code, and a Level-2 warning if it’s C++ code. Here’s some sample code that shows how to use a zero-length array.

struct D
    char y[10];

struct E
    char a[10];
    D d[0]; // Zero length array

int _tmain()
    E* e = (E*)malloc(sizeof(E) + sizeof(D) * 5);
    D* d = new D[5];
    memcpy(e->d,d,sizeof(D) * 5);
    delete d;
    return 0;