I have the following code:
#include <stdio.h>
int main(void) {
int array[0];
printf("%d", array);
return 0;
}
As we know, an array always points to its first item, but we don't have items in this example, but this code produces some memory address. What does it point to?
An array of size 0 is considered a constraint violation. So having such an array and attempting to use it triggers undefined behavior.
Section 6.7.6.2p1 of the C standard regarding constraints on Array Declarators states:
In addition to optional type qualifiers and the keyword
static
, the[
and]
may delimit an expression or*
. If they delimit an expression (which specifies the size of an array), the expression shall have an integer type. If the expression is a constant expression, it shall have a value greater than zero. The element type shall not be an incomplete or function type. The optional type qualifiers and the keywordstatic
shall appear only in a declaration of a function parameter with an array type, and then only in the outermost array type derivation
GCC will allow a zero length array as an extension, but only if it is the last member of a struct
. This is an alternate method of specifying a flexible array member which is allowed in the C standard if the array size is omitted.