2

What is the advantage of using zero-length arrays in C?

Eg:

struct email { time_t send_date; int flags; int length; char body[]; }list[0]; 
3
  • 2
    possible duplicate of Flexible array member in C-structure Commented Sep 13, 2012 at 17:59
  • @KeithMiller: Thats my question. Commented Sep 13, 2012 at 18:02
  • Oops I completely misread the question. I though you asked what is the disadvantage of using Zero Length arrays. Commented Sep 13, 2012 at 18:04

2 Answers 2

4

An array of size 0 is not valid in C.

char bla[0]; // invalid C code 

From the Standard:

(C99, 6.7.5.2p1) "If the expression is a constant expression, it shall have a value greater than zero."

So list declaration is not valid in your program.

An array with an incomplete type as the last member of a structure is a flexible array member.

struct email { time_t send_date; int flags; int length; char body[]; }; 

Here body is a flexible array member.

Sign up to request clarification or add additional context in comments.

11 Comments

True, but most compilers allowed you to get away with it, and it was commonly done before the flexible array member was codified. And yeah, people should have written body[1] when using the struct hack, but they didn't always. Such code should be pretty rare these days, so you may encounter it in the wild.
@dmckee Didn't they only let you get away with it as the last member of a struct, not as a freestanding array of length 0?
@DanielFischer Depended on the compiler. Some just let it slide so that they didn't have to special case the array hack.
@DanielFischer: There are a number of situations where being able to define a size-zero array and have it represent a pointer to the spot where the next struct element would go, would be useful. Many wouldn't require any special handling on the part of a typical compiler, beyond simply removing the code that triggers a compiler error on a zero-length array. Why should the compiler writer go out of his way to forbid something that could be useful? The only disadvantage I could see for allowing the construct would be that code like:
@DanielFischer: struct {unsigned char a; unsigned char NumAsBytes[0]; unsigned int num;} might not completely overlay NumAsBytes on num; to make it work properly, one would have to add an int dummy[0] before the NumAsByte[0] declaration to force the start of the array to be word aligned.
|
-1

Here is your answer: http://www.quora.com/C-programming-language/What-is-the-advantage-of-using-zero-length-arrays-in-C

2 Comments

One-link answers without any explication are generally frowned upon. At least quote said answer.
Agree. Unfortunately I was researching the same question a week back and couldn't explain better

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.