What happens if I define a 0-size array in C/C++?

2018-12-31 08:19发布

Just curious, what actually happens if I define a zero-length array int array[0]; in code? GCC doesn't complain at all.

Sample Program

#include <stdio.h>

int main() {
    int arr[0];
    return 0;
}

Clarification

I'm actually trying to figure out if zero-length arrays initialised this way, instead of being pointed at like the variable length in Darhazer's comments, are optimised out or not.

This is because I have to release some code out into the wild, so I'm trying to figure out if I have to handle cases where the SIZE is defined as 0, which happens in some code with a statically defined int array[SIZE];

I was actually surprised that GCC does not complain, which led to my question. From the answers I've received, I believe the lack of a warning is largely due to supporting old code which has not been updated with the new [] syntax.

Because I was mainly wondering about the error, I am tagging Lundin's answer as correct (Nawaz's was first, but it wasn't as complete) -- the others were pointing out its actual use for tail-padded structures, while relevant, isn't exactly what I was looking for.

标签: c++ c arrays
7条回答
姐姐魅力值爆表
2楼-- · 2018-12-31 08:58

Another use of zero-length arrays is for making variable-length object (pre-C99). Zero-length arrays are different from flexible arrays which have [] without 0.

Quoted from gcc doc:

Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure that is really a header for a variable-length object:

 struct line {
   int length;
   char contents[0];
 };

 struct line *thisline = (struct line *)
   malloc (sizeof (struct line) + this_length);
 thisline->length = this_length;

In ISO C99, you would use a flexible array member, which is slightly different in syntax and semantics:

  • Flexible array members are written as contents[] without the 0.
  • Flexible array members have incomplete type, and so the sizeof operator may not be applied.

A real-world example is zero-length arrays of struct kdbus_item in kdbus.h (a Linux kernel module).

查看更多
登录 后发表回答