Declaring and initializing an array
suggest changeThe general syntax for declaring a one-dimensional array is
type arrName[size];
where type could be any built-in type or user-defined types such as structures, arrName is a user-defined identifier, and size is an integer constant.
Declaring an array (an array of 10 int variables in this case) is done like this:
int array[10];
It now holds indeterminate values. To zero-initialize it, write:
int array[10] = {0};
Arrays can also have initializers, this example declares an array of 10 int’s, where the first 3 int’s will contain the values 1, 2, 3, all other values will be zero:
int array[10] = {1, 2, 3};
In the above method of initialization, the first value in the list will be assigned to the first member of the array, the second value will be assigned to the second member of the array and so on. If the 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 values[] = {1, 2, 3}; /* an array of 3 ints */
int designated[] = {[3] = 8, [0] = 9}; /* length is 4 */
Declaring an array of zero length is not allowed.
Variable-length arrays (VLAs) were added in C99 and made optional in C11. They differ from ordinary arrays in one important way: the length does not have to be known at compile time. A VLA has automatic storage duration. A VLA itself cannot have static storage duration, although a pointer to a VLA can.
size_t m = calc_length(); /* calculate array length at runtime */
int vla[m]; /* create array with calculated length */
Important:
VLAs are potentially dangerous. If vla requires more automatic storage than is available, the program fails; on many implementations that failure is a stack overflow. Style guides often discourage VLAs for that reason.