zero length arrays vs. pointers zero length arrays vs. pointers arrays arrays

zero length arrays vs. pointers


The only time I've ever seen zero-length arrays actually used is when you want to have a variable length structure.

As in this example taken from here

    struct line {       int length;       char contents[0];     };     struct line *thisline = (struct line *)       malloc (sizeof (struct line) + this_length);     thisline->length = this_length;

You don't want to use a pointer in the above struct as you want the contents to be part of the allocated memory of the structure.

If you do a sizeof on the above struct it doesn't include any space for the contents. I'm not sure if this ever made it into a standard, it gives warnings on various compilers.


ISO C forbids 0-length arrays.

char **c1;

This defines an object c1 of type pointer-to-pointer-to-char.

char *c2[0];

This is a compile-error. Not allowed. Not in C, not in C++.

struct a {  int i;  char c[0]; //sizeof(a) is sizeof(int)?  a.c == (&i)+1?};

Error as noted previously -- the size of an array must be greater than zero.

 struct a {  int i;  char c[1]; };

Also known as the struct-hack. Abused in low-level code on nearly all OSes -- Linux, Windows.

C99 does give us a sizeless array better known as flexible-array member:

struct a {  int i;  char c[]; /* note: no size */ };


You might get some answers here from the GCC docs. But that focuses on the topic of having a zero-length array as the last members of the struct. It doesn't give direct answers regarding sizeof.

(As has been made clear by others, zero-length arrays aren't in standard C, but they were in GNU C.)