Arrays are the first structured type that we have seen. It is defined as a contiguous sequence of elements of the same size. The type of these elements is known as the base type. Being of the same size means they are of the same type. The objects can be of any type as long as they are all the same. The size of an array is fixed at compile time. Some languages, like C and BASIC, give the illusion of variable sized arrays but in reality, the values are copied from the old array to a new larger one. The old one is not extended. Since the elements are contiguous, we can directly calculate the address of any elements given three pieces of information.
We need the size of the elements, the address of the first element and the number of the element in the array. The expression for doing this is:
initial_address + (element#) * size_of_base_typeFor example, if we had an array of integers (each two bytes long) that started at address 15, the location in memory (the address) of element 10 is
15 + (10) * 2 = 35
Arrays in C++ start with an element number of 0. This is important to remember as people usually start counting at 1.
Multi-dimensional arrays are stored as sequences of one dimensional arrays. An NxM array has N rows and M columns. Either each row is stored (row major) or each column (column major). The calculation above is extended again to first find the row we want by changing element# to row# and size_of_object to size_of_row. This gives us the initial address of the row we want and we use exactly the first version of the expression to calculate the column address. First the row address
initial_address + (row# - initial_row#) * size_of_row
Then find the column within that row
row_address + (element# - initial_element#) * size_of_base_type
Arrays are characterized by fast random access. Any element on the array
can be found as fast as any other. They are however, limited to the size
originally allocated and all the elements must be the same size. It
is also difficult to insert or delete elements