23-01-2012, 02:15 PM
Arrays
[attachment=16446]
Rows and tables of storage.
Arrays are a convenient way of grouping a lot of variables under a single variable name. Arrays are like pigeon holes or chessboards, with each compartment or square acting as a storage place; they can be one dimensional, two dimensional or more dimensional! An array is defined using square brackets []. For example: an array of three integers called "triplet" would be declared like this:
int triplet[3];
Notice that there is no space between the square bracket [ and the name of the array. This statement would cause space for three integers type variables to be created in memory next to each other as in the diagram below.
------------------------------------
int triplet: | | | |
------------------------------------
Why use arrays?
Arrays are most useful when they have a large number of elements: that is, in cases where it would be completely impractical to have a different name for every storage space in the memory. It is then highly beneficial to move over to arrays for storing information for two reasons:
• The storage spaces in arrays have indicies. These numbers can often be related to variables in a problem and so there is a logical connection to be made between an array an a program.
• In C, arrays can be initialized very easily indeed. It is far easier to initialize an array than it is to initialize twenty or so variables.