next up previous contents
Next: 8.2 Passing Arrays as Up: 8 Arrays and Pointers Previous: 8 Arrays and Pointers

8.1 Declaring and Initializing Arrays

Arrays are declared using the square brackets. The following statement declares an array of ten integers:

    int foo[10];

In this array, elements are numbered from 0 to 9. Elements are accessed by enclosing the index number within square brackets:

foo[4] denotes the fifth element of the array foo (since counting begins at zero).

Arrays are initialized by default to contain all zero values; arrays may also be initialized at declaration by specifying the array elements, separated by commas, within curly braces. Using this syntax, the size of the array would not specified within the square braces; it is determined by the number of elements given in the declaration. For example,

    int foo[]= {0, 4, 5, -8,  17, 301};

creates an array of six integers, with foo[0] equalling 0, foo[1] equalling 4, etc.

Character arrays are typically text strings. There is a special syntax for initializing arrays of characters. The character values of the array are enclosed in quotation marks:

    char string[]= "Hello there";

This form creates a character array called

string with the ASCII values of the specified characters. In addition, the character array is terminated by a zero. Because of this zero-termination, the character array can be treated as a string for purposes of printing (for example). Character arrays can be initialized using the curly braces syntax, but they will not be automatically null-terminated in that case. In general, printing of character arrays that are not null-terminated will cause problems.

Fred G. Martin
Fri Mar 29 17:44:15 EST 1996