Arrays
So far. The only variables we ve seen are
scalar: capable of holding a single data item. C also supports aggregate
variables, which can store collections of values. There are two kinds of
aggregates in C: arrays and structures.
One-Dimensional
Arrays
An array is a data structure containing a
number of data values, all of which have the same type. These values, known as
elements. can be individually selected by their position within the array.
The simplest kind of array has just one dimension. The elements of a one-
dimensional array are conceptually arranged one after another in a single row
(or column, if you prefer). Here's how we might visualize a one-dimensional
array named a:
|
|
|
|
|
|
|
|
|
|
a
To declare an array, we must specify the type
of the array's elements and the number of elements. For example, to
declare that the array a has 10 elements of type int. we would write
int a [10];
The elements of an array may be of
any type; the length of the array can be specified by any (integer) constant
expression. Since array lengths may need to be adjusted when the program is
later changed, using a macro to define the length of an array is an excellent
practice:
#define N 10
int a [N] ;
Array Subscripting
To
access a particular element of an array, we write the array name followed by an
integer value in square brackets (this is referred to as subscripting or
indexing the array). Array elements are always numbered starting from 0, so
the elements of an array of length n are indexed from 0 to n - i.
For example, if a is an array with 10
elements, they're designated by a [0]. a [1] a [9], as the following figure
shows:
a[0]
a[l] a[2] a[3J al4] a[5] a[6] a[7] a[8] a[9]
Expressions
of the form a [ i] are lvalues, so they can be used in the same way as ordinary
variables:
a[0]
= 1;
printf ("%d\n", a [5]),- ++a[i] ;
In general, if an array contains elements of type T.
then each element of the array is treated as if it were a variable of type
T. In this example, the elements a [0], a [5]. and a [i] behave like int
variables.
Arrays and
for loops go hand-in-hand. Many programs contain for loops whose job is to
perform some operation on every element in an array.
Array Initialization
An array, like any other variable, can be given an initial value at the
time it's declared. The rules are somewhat tricky, though, so we'll cover some
of them now and save others until later.
The most common form
of array initializer is a list of constant expressions enclosed in braces and separated by
commas:
int a[10] =
{l, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Designated Initializers
It's
often the case that relatively few elements of an array need to be initialized
explicitly; the other elements can be given default values. Consider the
following example:
int a [15] = {0, 0, 29, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0,
48};
We want element 2 of the array to be 29, element 9 to be 7,
and element 14 to be 48, but the other values are just zero. For a large array,
writing an initializer in this fashion is tedious and error-prone (what if
there were 200 zeros between two of the nonzero values?).
C99's
designated initializers can be used to solve this problem. Here's how
we could redo the previous example using a designated initializer:
int a [15] = { [2] = 29, [9] = 7, [14] = 48};
Each
number in brackets is said to be a designator.
Besides
being shorter and easier to read (at least for some arrays), designated
initializers have another advantage: the order in which the elements are listed
no longer matters. Thus, our previous example could also be written in the
following way:
int a [15] = {[14] = 48, [9] = 7, [2] = 29};
Designators must be integer constant expressions. If the
array being initialized has length n, each designator must be between 0 and n-
I. However, if the length of the array is omitted, a designator can be any
nonnegative integer. In the latter case, the compiler will deduce the length of
the array from the largest designator.
Using
the sizeof Operator with Arrays
The sizeof
operator can determine the size of an array (in bytes). If a is an array of 10
integers, then sizeof (a) is typically 40 (assuming that each integer requires
four bytes).
We can
also use sizeof to measure the size of an array element, such as a [0].
Dividing the array size by the element size gives the length of the array:
sizeof(a) / sizeof(a[0]).
Multidimensional Arrays
An array may have any number of
dimensions. For example, the following declaration creates a two-dimensional
array (a matrix, in mathematical terminology):
int m[5] [9] ;
The array m has 5 rows and 9
columns. Both rows and columns are indexed.
Multidimensional arrays play a lesser role in C
than in many other programming languages, primarily because C provides a more
flexible way to store multidimensional data: arrays of pointers.
Constant Arrays
Any
array, whether one-dimensional or multidimensional, can be made
"constant" by starting its declaration with the word const:
const
char hex_chars[] ={'0', ‘1', ‘2’, '3', '4',
'5', ‘6', '7', '8', '9', 'A', 'B', 'C', 'D', ' E' , 'F'};
An array that's been declared const should not be modified by the
program: the compiler will detect direct attempts to modify an element.
Declaring
an array to be const has a couple of primary advantages. It documents that the
program won't change the array, which can be valuable information for someone
reading the code later. It also helps the compiler catch errors, by informing
it that we don't intend to modify the array.
const
isn't limited to arrays; it works with any variable, as we'll see later. However,
const is particularly useful in array declarations, because arrays may contain
reference information that won't change during program execution.
No comments:
Post a Comment