Oleksandr Novik
Oleksandr Novik

Reputation: 738

What is the nature of an empty array in C?

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?

Upvotes: 1

Views: 149

Answers (1)

dbush
dbush

Reputation: 223972

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 keyword static 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.

Upvotes: 6

Related Questions