Page 45 - C-Language
P. 45
list size is smaller than the array size, then as in the above example, the remaining members of
the array will be initialized to zeros. With designated list initialization (ISO C99), explicit
initialization of the array members is possible. For example,
int array[5] = {[2] = 5, [1] = 2, [4] = 9}; /* array is {0, 2, 5, 0, 9} */
In most cases, the compiler can deduce the length of the array for you, this can be achieved by
leaving the square brackets empty:
int array[] = {1, 2, 3}; /* an array of 3 int's */
int array[] = {[3] = 8, [0] = 9}; /* size is 4 */
Declaring an array of zero length is not allowed.
C99C11
Variable Length Arrays (VLA for short) were added in C99, and made optional in C11. They are
equal to normal arrays, with one, important, difference: The length doesn't have to be known at
compile time. VLA's have automatic storage duration. Only pointers to VLA's can have static
storage duration.
size_t m = calc_length(); /* calculate array length at runtime */
int vla[m]; /* create array with calculated length */
Important:
VLA's are potentially dangerous. If the array vla in the example above requires more space on the
stack than available, the stack will overflow. Usage of VLA's is therefore often discouraged in style
guides and by books and exercises.
Clearing array contents (zeroing)
Sometimes it's necessary to set an array to zero, after the initialization has been done.
#include <stdlib.h> /* for EXIT_SUCCESS */
#define ARRLEN (10)
int main(void)
{
int array[ARRLEN]; /* Allocated but not initialised, as not defined static or global. */
size_t i;
for(i = 0; i < ARRLEN; ++i)
{
array[i] = 0;
}
return EXIT_SUCCESS;
}
https://riptutorial.com/ 21

