Array

From GPWiki
Jump to: navigation, search

Arrays are a very simple data structure. Arrays use a single variable name to store multiple values. The different values are usually referenced by a number, often called index. This is a very convenient thing to do, as it keeps us from creating variables such as a1, a2, a3, a4 and so on. The benefit is especially noticable when you need several hundred variables that hold similar data.

The implementation almost always goes like this: A data block big enough to hold the requested number of elements is created, and when indexing the array the location of the indexed element is found by adding I (index) times the size of one element to the location of the start of the array.

Almost every programming language (except for some esoteric ones) offers arrays. Sometimes they are called vectors. Some even offer multi-dimensional arrays, but this can easily be simulated - for example in two dimensions (X x Y) you make your array size X * Y and index element (N, M) with index (N + M * X).

A useful extension to the idea of an array is dynamic arrays, which can grow on their own and typically support some kind of operation to add and remove elements to the end of them (they can be used as stacks too!). They are implemented by reallocating a bigger block for the array whenever it gets too big and copying the old elements into that block. They come pre-implemented in many languages. All arrays in VB are dynamic, resizable with ReDim. C++ includes std::vector, which implements a dynamic array.