Page 34 - Programming Microcontrollers in C
P. 34
Arrays 19
The argument of an array is sometimes called its index. It is a num
ber that selects a specific entry into an array. Array arguments start
with zero always. Therefore, when an array of 100 elements is cre
ated, these elements are accessed by using the arguments 0 to 99.
The standard requires that the first element beyond the end of the
array be accessible as an array entry. Attempts to access elements
beyond that will give undefined results.
Arrays can be initialized at declaration. The initialization values
must be enclosed in braces, and if there are several individual nu
merical values, these values must be separated by commas. In the
case of a string initialization, it is necessary to include the string in
quotes and also enclose the string along with its quotation marks
within the braces. In both of these cases, the size of the array is
calculated at compile time, and it is unnecessary for the programmer
to figure the size of the array.
A string is a special case of an array. Whenever a string is gener
ated in C, an array of characters is created. The length of the array is
one greater than the length of the string. The individual characters
from the string are placed in the array entries. To be a proper C
string, the array’s last character must be a zero or a null. All strings
in C are null terminated. If you as a programmer create a string in
your program, you must append a null on the end of the character
array to be guaranteed that C will treat the array as a string.
If the programmer should specify an array size and then initial
ize a portion of the array like
int time[6]={1,5,3,4};
the compiler will initialize the first four members of the array with
the specified values and initialize the remainder of the array with
zero values. This approach allows you to initialize any array with all
zero values by
long ziggy[100]={0};
which will fill all of the elements of the array ziggy[] with zeros.
C provides you with no array boundary checking. It is the
programmer’s responsibility to guarantee that array arguments do
not violate the boundaries of the array.