In general, from the point of view for memory access, this is fine, because, unless the operand of sizeof
is of VLA type, they are not evaluated. So, in this case, x[0]
is not an invalid memory access.
Quoting C11
, chapter §6.5.3.4, emphasis mine
The sizeof
operator yields the size (in bytes) of its operand, which may be an
expression or the parenthesized name of a type. The size is determined from the type of
the operand. The result is an integer. If the type of the operand is a variable length array
type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an
integer constant.
In a broad sense, for an array like
int arr[5]= {0};
writing
sizeof(arr)/sizeof(arr[10]);
is also valid as arr[10]
is not being evaluated, it's only about the size of the operand, not the content (so, needs no dereferencing).
That said,
- zero-length arrays are not standard C, they are gcc extension.
sizeof
yields a results of size size_t
, so we should use %zu
format specifier to print the result.