Arrays
Introduction
Most programming languages offer the array data structure as a basic
language element.
Arrays are often used to implement other data structures,
such as queues, stacks, lists and hash tables.
An array is a collection of individual data elements
that is:
- Ordered -- we can count off the elements 0,1,2,3,...
- Fixed in size
- Homogeneous -- all of the elements have to be of the
same type, e.g., int, float, char, etc.
In C, each array has two fundamental properties:
- the element type
- the size
Declaring Arrays
The general form of an array declarations:
elementtype arrayname [ arraysize ] ;
Examples of array declarations:
int array [10];
int rolls [HIGH + 1];
double scores [ENROLLMENT];
What happens in memory ?
The array declaration:
int sample [5];
would cause space to be allocated that is big enough to hold 5 ints
contiguously, as shown:
Accessing array elements
We can select a particular array element by giving it's index .
In C, the elements of an array with N elements are indexed by the
integers 0, 1, 2, 3, ... (N-1).
The general form then:
arrayname [ indexValue ]
Examples:
sample [2] = 25;
would cause the element at index 2 to be assigned the value 25
The following code:
/* Initialization of all of the
elements of the array to 0 */
for (i = 0; i < 5; i++)
{
sample [i] = 0;
}
would cause all of the elements of the array to be set to 0
Multi-dimensional Arrays
If data elements of an array are arrays themselves, it is called a
multidimensional array.
Although a two-dimensional array is really an array of arrays, it is
more typical to think of it as a two dimensional table.
Multidimensional arrays are also commonly used. Up to three subscripts
is not unusual. ANSI C requires that an implementation allow
multidimensional arrays of at least six dimensions.
Uses of Arrays
The simple uses of arrays include anything where many values of
the same data type need to be kept for a particular
purpose. Vectors in physics, matrices in linear algebra, or anything
that can be thought of as a "table".