7.2 Defining Arrays
An array in C can be either static or dynamic, depending on when it is created. A static array is one in which the size is known at compile-time. Thus, its size must be a literal or the value of a constant variable that is specified when the program is compiled. A dynamic array, on the other hand, is created at run-time and its size can be determined during execution of the program. For now, we focus on static arrays and defer consideration of dynamic arrays until later in the chapter.
Array Declarations
Arrays in C can only store values of a specified data type, similar to variables. To create a static array you must specify three pieces of information:
- the name of the array
- the number of elements in the array, and
- the type of data stored in each element.
For example, the declaration:
- int grades[11];
creates an array with the name grades that contains 11 elements, all of which store integer values.
Note that the elements of the array are not initialized to any given value, but will contain the values that are currently stored in the memory location where the array is created.
|
Defining an Array
type name[size];
|
An array can be created to store any type of data. For example, we can create an array to store real values or individual characters:
- float scores[5];
- char code[8];
Provide the C code to declare an integer array named states that contains 50 elements.
- int states[50];
Array Size
As indicated earlier, when a static array is created, the size of the array must be known at compile time. Thus, the array size must be either a literal integer value or a constant integer variable. For example,
- const int MAX_SIZE = 100;
- int main()
- {
- int grades[11];
- int values[MAX_SIZE]
- float temp[MAX_SIZE + 1];
- }

Do not use a non-constant variable to specify the size of an array. While the following will compile and execute,
- int main()
- {
- int n;
- scanf("%d", &n);
- int values[n];
- }
the results will be unpredictable because the array would have been created at compile time with a size of 0, which can be accessed and used.
Consider the array declaration below. How many elements does the array contain?
- float xcoords[4];
- 1
- 3
- 4
- 5

