When an array is defined with []
for the dimension and an initialization is given, its size is deduced from the initializers. However, = {}
has no initializers. This does not conform to the formal grammar in C, which specifies there shall be at least one initializer inside the braces (C 2018 6.7.9 1). Because of this, the behavior is not defined by the C standard, except that a conforming compiler must produce a diagnostic message.
Some compilers accept this declaration and treat it as an array of zero length. This is another reason the behavior is not defined by the C standard, as the standard defines an array to be a nonempty set of objects (C 2018 6.2.5 20).
The program then goes on to attempt to put values in num[0]
, num[1]
, num[2]
, and num[3]
. Since the array has zero length, these elements do not exist in the C computing model, and no memory has been reserved for them. The scanf
calls likely write these values into memory that the program is using for other purposes. And, since the program is using that memory for other purposes, it may change that memory, resulting in the values later accessed by num[0]
, num[1]
, num[2]
, or num[3]
to be different from what scanf
wrote there.
Can I declare an array in C without declaring its size and element?
You can declare an array without specifying its size. At file scope, outside of any function, int num[];
would be a valid declaration that tells the compiler an array named num
may be defined somewhere else.
When you define an array, you should specify its size, either by explicitly giving the size inside []
(as with int num[3];
) or by giving initial values from which the compiler can deduce the size (as with int num[] = { 9, 8, 7, 6 };
). Inside the body of a function, a declaration of an array without extern
is also a definition, so it should include the size.