An array can be used to store and manipulate a collection of data that is all of the same type.
The indexed variables of an array can be used just like any other variables of the base type of the array.
A for
loop is a good way to step through the elements of an array and perform some program action on each indexed variable.
The most common programming error made when using arrays is attempting to access a nonexistent array index. Always check the first and last iterations of a loop that manipulates an array to make sure it does not use an index that is illegally small or illegally large.
An array formal parameter is neither a call-by-value parameter nor a call-by-reference parameter, but a new kind of parameter. An array parameter is similar to a call-by-reference parameter in that any change that is made to the formal parameter in the body of the function will be made to the array argument when the function is called.
The indexed variables for an array are stored next to each other in the computer’s memory so that the array occupies a contiguous portion of memory. When the array is passed as an argument to a function, only the address of the first indexed variable (the one numbered 0) is given to the calling function. Therefore, a function with an array parameter usually needs another formal parameter of type int
to give the size of the array.
When using a partially filled array, your program needs an additional variable of type int
to keep track of how much of the array is being used.
To tell the compiler that an array argument should not be changed by your function, you can insert the modifier const
before the array parameter for that argument position. An array parameter that is modified with a const
is called a constant array parameter.
If you need an array with more than one index, you can use a multidimensional array, which is actually an array of arrays.