An array is an aggregate data type whose individual data items are called elements and are accessed with an index or subscript number. Arrays order their elements, so an index number always refers to the same element. Computers can move the array elements around in a program as a group using the array name, and they can access individual array elements with the array name and an index number.
(a) | (b) |
C++ arrays are said to be zero-indexed, which means that the first element in the array is at index value 0. So, valid index values must be in the range 0 to size-1 (i.e., 0 ≤ index ≤ size-1 or 0 ≤ index < size)
C++ does not check that index values are within the valid range, and an incorrect index value might crash the program, return a meaningless value, or corrupt data near the array in memory.
Arrays | Structs | |
---|---|---|
Contained Data | All elements are the same type | Fields or elements may be different types |
Specification | N/A | struct part } int code; double cost; }; |
Definition | int test[10]; "10" is the size of the array |
part widget; |
Element Access | By index or subscripttest[5] brackets are the selection operator & "5" is the index value |
By namewidget.cost "." (i.e., dot) is the selection operator |