What Is An Array?

 < Day Day Up > 



An array is a contiguous allocation of memory to homogeneous objects. Contiguous means the objects are stored in memory one after the other. Homogeneous means the objects in the array are of the same type. Figure 8-1 shows an array of 4 integer objects.

click to expand
Figure 8-1: Array of Four Integer Objects

The array begins at a certain memory address. Each integer object in the array follows the one before it and is located at a memory address one allocation unit higher than the previous object in the array. In the case of integers, an allocation unit is equal to four bytes on a 32-bit machine, since an integer occupies four bytes of memory. As an example, if the integer array shown in figure 8-1 starts at memory address 0010, then the next integer object will be located at memory address 0014, the next at memory address 0018, and the last at memory address 001C.

Locating Array Elements

Each object in an array is referred to as an array element. Individual array elements are accessed by combining the starting address of the array with a memory address offset that points to the beginning of the particular array element. The offset address is calculated by multiplying the size of an array object in bytes by the number of the element to be accessed minus 1. For instance, to access the third array element in the integer array shown in figure 8-1, the address of the beginning of the array, 0010, is added to the offset, (4 bytes x (3 -1)) = 8, to yield an element address of 0018. Thus, the third element of the array is located at memory address 0018.

You may be wondering why you need to subtract one from the element number. Since the first element of the array is located at the start of the array, no offset is required to access the first element. In other words, the address of the start of the array points to the first element of the array, the second element of the array is located one allocation unit from the start of the array, the third element is located two allocation units from the start of the array, and so on. Remember, the size of the allocation unit used to calculate array element offsets depends on the type of objects the array is declared to contain.

Fortunately, C++ provides a convenient notation for accessing array elements that is discussed in the next section.



 < Day Day Up > 



C++ for Artists. The Art, Philosophy, and Science of Object-Oriented Programming
C++ For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504028
EAN: 2147483647
Year: 2003
Pages: 340
Authors: Rick Miller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net