In an array declaration, the number between the [
and ]
specifies the number of elements in the array.
The code in your question:
char number_str[];
sprintf(number_str, "%lld", number_ll);
is illegal. If it appears inside a function definition, then you cannot use empty brackets; you must specify the size of the array -- and a call to sprintf
, or to any other function, can only appear inside a function definition.
If you do specify the size of the array:
char number_str[100];
sprintf(number_str, "%lld", number_ll);
that creates an object number_str
which is an array of 100 char
elements. If you make the array too small:
char number_str[3];
sprintf(number_str, "%lld", number_ll); /* let's say number_ll == 12345 */
then your program may appear to work, but in fact its behavior is undefined. The sprintf
call will attempt to store 6 characters in a 3-character array.
A C compiler is not obliged to diagnose this error. It will very likely let you try to do this, resulting in data being written into memory areas that you don't own.
At file scope, you can declare something like:
extern char array[];
which specifies that an object called array
, of type array (of some unspecified size) of char
is defined elsewhere.
As a (rather annoying) special case, a function parameter defined with the syntax of an array is actually a pointer:
void func(char param[42]) {
/* param is a pointer; the 42 is silently ignored */
}
Always remember that arrays and pointers are two different things. For an explanation of their admittedly confusing relationship, see section 6 of the comp.lang.c FAQ.