Sunday, September 26, 2010

Single-Dimension Arrays

The general form for declaring a single-dimension array is
type var_name[size];
Like other variables, arrays must be explicitly declared so that the compiler may
allocate space for them in memory. Here, type declares the base type of the array, which
is the type of each element in the array, and size defines how many elements the array
will hold. For example, to declare a 100-element array called balance of type double,
use this statement:
double balance[100];
An element is accessed by indexing the array name. This is done by placing the
index of the element within square brackets after the name of the array. For example,
balance[3] = 12.23;
assigns element number 3 in balance the value 12.23.
In C/C++, all arrays have 0 as the index of their first element. Therefore, when
you write
char p[10];
you are declaring a character array that has ten elements, p[0] through p[9]. For
example, the following program loads an integer array with the numbers 0 through 99:
#include <stdio.h>
int main(void)
{
int x[100]; /* this declares a 100-integer array */
int t;
/* load x with values 0 through 99 */
for(t=0; t<100; ++t) x[t] = t;
/* display contents of x */
for(t=0; t<100; ++t) printf("%d ", x[t]);
return 0;
}
The amount of storage required to hold an array is directly related to its type and
size. For a single-dimension array, the total size in bytes is computed as shown here:
total bytes = sizeof(base type) x size of array
C/C++ has no bounds checking on arrays. You could overwrite either end of an
array and write into some other variable's data or even into the program's code. As the
programmer, it is your job to provide bounds checking where needed. For example,
this code will compile without error, but is incorrect because the for loop will cause the
array count to be overrun.
int count[10], i;
/* this causes count to be overrun */
for(i=0; i<100; i++) count[i] = i;
Single-dimension arrays are essentially lists of information of the same type that are
stored in contiguous memory locations in index order. For example, Figure 4-1 shows
how array a appears in memory if it starts at memory location 1000 and is declared as
shown here:
char a[7];
Element a[0] a[1] a[2] a[3] a[4] a[5] a[6]
Address 1000 1001 1002 1003 1004 1005 1006
Figure 4-1. A seven-element character array beginning at location 1000

No comments:

Post a Comment