Sign in Join
Wiki copytemporary

Array: what changed

Revision 2 to 3. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11An **array** is a linear data structure concept that groups elements of the same type, stores them in contiguous and adjacent memory locations and provides random access to all of said elements (also known as components) by way of a linear index.
22
33The word `array` is a [[Reserved word|reserved word]]. It always occurs in conjunction with the word [[Of|`of`]].
44
55## Notion
66
77An `array` is a limited and arranged aggregation of elements, all having the same [[Data type|data type]] which is called the “base type.” It has at least one discrete, bounded dimension and continuously enumerates all of its elements. Each element can be uniquely identified by one or more scalar values, called _indices_ , along those dimensions.
88
99A one-dimensional `array` resembles an **n-tuple** , as it is known in mathematics, but has the constraint of being homogenous (all elements must be of the same type). The range of all possible values such an `array` can acquire is the homogenous n-ary Cartesian product of the base type.
1010
1111A two-dimensional `array` resembles the mathematical concept of a **matrix** , except for the homogeneity restriction.
1212
1313## Usage
1414
1515### Length
1616
1717Originally, Pascal only provided arrays of fixed length ([[Standard Pascal]]), meaning the number of elements an array consisted of had to be known at compile-time. Since this turned out to be a major constraint, and changes in computer hardware since then justified a step forward, variable-length arrays were introduced.
1818
1919[[Extended Pascal]] defined the notion of “schemata” for this. [[Delphi]] introduced “dynamic arrays”. As of 2020, [[FPC]] only supports the latter regarding variable-length arrays, while support for “schemata” is planned.
2020
2121Depending on whether an array is intended of being capable of changing its size, its definition varies, but just marginally. For a one-dimensional static array, the type definition looks like this:
2222```
2323array[indexType] of baseType
2424```
2525
2626A dynamic array type definition is simply relieved of its dimension specification:
2727```
2828array of baseType
2929```
3030
3131### Static arrays
3232
3333In static arrays, the ranges of all dimensions are known in advance. All dimension specifications have to be ordinal types. The following code shows some valid array definitions, all of them static.
3434```
3535program staticArrayDemo(input, output, stderr);
3636
3737 type
3838 // specifying ordinal types as index directly
3939
4040 /// allows selection of a character
4141 /// based on a Boolean value
4242 characterChoice = array[boolean] of UCS4char;
4343
4444 // enumerations
4545
4646 /// enumerates Cartesian axes
4747 spaceAxis = (xAxis, yAxis, zAxis);
4848 /// a point in three-dimensional Euclidean space
4949 locus = array[spaceAxis] of valReal;
5050 /// a point in a two-dimensional Euclidean plane
5151 point = array[xAxis..yAxis] of valReal;
5252
5353 // integer subranges
5454
5555 level = array[-24..24] of longint;
5656 box = array[-1..1, -1..1, -1..1] of boolean;
5757 transformationMatrix = array[0..1, 0..1] of valReal;
5858 begin
5959 end.
6060```
6161
6262As all of an array’s elements have to be addressable, there exists a maximum limit of elements an array can hold. The [[SizeOf|`sizeOf`]] every array type has to be less than [`ptrInt`](<https://www.freepascal.org/docs-html/rtl/system/ptrint.html>)’s maximum value.
6363
6464### Initialization
6565
6666It's possible to set the initial values of a static (and dynamic) array's elements when it is declared –
6767```
6868var
6969 SArray : array[0..2] of integer = (1,2,3); // A static Array
7070 CArray : array[0..1] of TColor = (clRed, clBlue); // A static Array
7171```
7272
7373**See more:** [Topic: How to initialize the array (Free Pascal Lazarus Forum)](<https://forum.lazarus.freepascal.org/index.php/topic,52656.0.html>)
7474
7575### Addressing elements
7676
7777An array’s element is addressed by naming the array variable’s identifier, followed by a valid index value enclosed by square brackets.
7878```
7979program arrayAddressDemo(input, output, stderr);
8080 var
8181 msg: array[0..2] of char;
8282 begin
8383 msg[0] := 'H';
8484 msg[1] := 'i';
8585 msg[2] := '!';
8686 writeLn(msg);
8787 end.
8888```
8989
9090Multidimensional arrays’ elements can be addressed in two ways: either by [[Comma|comma]]-separated indices…
9191```
9292arrayVariable[firstDimensionIndex, secondDimensionIndex, thirdDimensionIndex]
9393```
9494
9595…or by putting indices in dedicated square brackets.
9696```
9797arrayVariable[firstDimensionIndex][secondDimensionIndex][thirdDimensionIndex]
9898```
9999
100100A third syntactically-valid option would be mixing both styles, however that is considered poor style, unless perhaps there is indication to group indices (e.g. `x`, `y` and `z` coordinates versus other indices) it is okay. Nonetheless, only the first mentioned notation is valid while defining array types.
101101
102102Note, it is very important to specify indices in the defined order, within each dimensions’ range. Consider the following program; it will compile, but fail during [[runtime|run-time]] due to `{$rangeChecks on}`:
103103```
104104program arrayAddressOrderDemo(input, output, stderr);
105105 {$rangeChecks on}
106106 var
107107 i: integer;
108108 f: array[0..1, 0..3] of boolean;
109109 begin
110110 for i := 0 to 7 do
111111 begin
112112 f[0, i] := true;
113113 end;
114114 end.
115115```
116116
117117While the program would indeed iterate over every array’s elements, it doesn’t do so in the intended way, but rather exploits the fact that the array’s internal memory structure is just a continuous block of memory. This is bad style. A programmer working with a high-level language is not supposed to care about specific memory layouts. Cave: It is possible to tamper with other variables in this way. At any rate, a [[runtime error|run-time error]], namely “RTE 216 general protection fault,” will occur if an attempt is made to access memory which is not within the purview of the process owner.
118118
119119When values contained in arrays are merely read (and thus the indices do not matter), a [[for-in loop|`for … in` loop]] can be used.
120120
121121## Dynamic arrays
122122
123123A [[Dynamic array|dynamic array]] is an approach for overcoming the limitation of knowing the sizes of all dimensions in advance. See its dedicated page for more details.
124124
125125## Application
126126
127127See, for instance:
128128
129129 * [[Array sort]]
130130 * [[15-puzzle]]’s and [[Peg Solitaire tutorial|Peg]]’s game board states are stored as an array.
131131
132132In the default [[RTL]]’s system unit, the function [`system.slice`](<https://www.freepascal.org/docs-html/rtl/system/slice.html>) returns the initial part of an array, similar to the Ruby notation `arrayVariable[0, n]`. Furthermore, there is [`system.arrayStringToPPchar`](<https://www.freepascal.org/docs-html/rtl/system/arraystringtoppchar.html>). Most [[Functions for descriptive statistics|statistical routines of the RTL’s math unit]] accept arrays as parameters, as well as some other routines.
133133
134134## See also
135135
136136 * [[Type information]]
137137 * [[Defensive programming techniques]]
138138 * [[Vectorization]]
139139 * [[Flexible Array Member]]
140140 * Tutorial: [[Basic Pascal Tutorial/Chapter 5/1-dimensional arrays|1-dimensional arrays]]
141141 * Tutorial: [[Basic Pascal Tutorial/Chapter 5/Multidimensional arrays|Multidimensional arrays]]
142142 * Example: [[Example: Multidimensional dynamic array|Multidimensional dynamic array]]
143143 * Article: [[Why Pascal is Not My Favorite Programming Language|Why Pascal is not my favorite programming language § “The size of an array is part of its type”]]
144144 * [`matrix` unit](<https://www.freepascal.org/docs-html/rtl/matrix/index.html>)
145145
146146
147147
148-navigation bar: data types [[simple type|simple data types]] | [[Boolean|`boolean`]] [[Byte|`byte`]] [[Cardinal|`cardinal`]] [[Char|`char`]] [[Currency|`currency`]] [[Double|`double`]] [`dword`](</index.php?title=DWord&action=edit&redlink=1> "DWord \(page does not exist\)") [[Extended|`extended`]] [[Int8|`int8`]] [[Int16|`int16`]] [[Int32|`int32`]] [[Int64|`int64`]] [[Integer|`integer`]] [[Longint|`longint`]] [[Real|`real`]] [[Shortint|`shortint`]] [[Single|`single`]] [[Smallint|`smallint`]] [[Pointer|`pointer`]] [[QWord|`qword`]] [[Word|`word`]]
149----|---
150-complex data types | `array` [[Class|`class`]] [[Object|`object`]] [[Record|`record`]] [[Set|`set`]] [[String|`string`]] [[Shortstring|`shortstring`]]
151-
152-
153-
154-****
148+**navigation bar: data types**
149+
150+_[[simple type|simple data types]]:_ [[Boolean|`boolean`]] [[Byte|`byte`]] [[Cardinal|`cardinal`]] [[Char|`char`]] [[Currency|`currency`]] [[Double|`double`]] [[DWord|`dword`]] [[Extended|`extended`]] [[Int8|`int8`]] [[Int16|`int16`]] [[Int32|`int32`]] [[Int64|`int64`]] [[Integer|`integer`]] [[Longint|`longint`]] [[Real|`real`]] [[Shortint|`shortint`]] [[Single|`single`]] [[Smallint|`smallint`]] [[Pointer|`pointer`]] [[QWord|`qword`]] [[Word|`word`]]
151+
152+_complex data types:_ `array` [[Class|`class`]] [[Object|`object`]] [[Record|`record`]] [[Set|`set`]] [[String|`string`]] [[Shortstring|`shortstring`]]
155153
156154---
157155*From the Free Pascal wiki, page "Array", as the Internet Archive kept it on 2026-01-21, last changed on 2024-11-03. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history