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

后端 未结 7 1566
轻奢々
轻奢々 2020-11-22 03:47

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

7条回答
  •  半阙折子戏
    2020-11-22 04:19

    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).

提交回复
热议问题