Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 36 ยท Records, Arrays and Pointers

Arrays in Pascal: Static, Dynamic and Open

Master Pascal arrays: static arrays with any index range, multidimensional arrays, dynamic arrays with SetLength, copying, sorting basics, open array parameters and range checking.

An array stores many values of the same type under one name, each reached by an index. Pascal's arrays are more flexible than those in most languages: the index does not have to start at zero, and it can even be a character or an enumeration. There are also two families, static arrays whose size is fixed at compile time and dynamic arrays that you resize while the program runs.

Pascal code is read-only here, and the runnable demos are C stand-ins.

Static arrays

You declare the index range between square brackets:

PASCAL
program StaticArrays;

var
  scores: array[1..5] of Integer;
  i, total: Integer;

begin
  for i := 1 to 5 do
    scores[i] := i * 10;
  total := 0;
  for i := Low(scores) to High(scores) do
    total := total + scores[i];
  WriteLn('Total: ', total);          { 150 }
  WriteLn('Count: ', Length(scores)); { 5 }
end.

Key points:

  • array[1..5] of Integer has five elements with indexes 1 to 5. You choose the bounds: array[0..9], array[-5..5], array['a'..'z'].
  • Use Low(a) and High(a) instead of hard-coding the bounds, so changing the declaration updates all loops.
  • Static arrays are copied by value: b := a copies every element.
  • Out-of-range access is not detected unless you enable range checking with {$R+}; then it raises an error. Without it you corrupt memory silently.

Arrays can be indexed by an enumeration, which gives readable code and a handy way to print names:

PASCAL
type
  TDay = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);

const
  DayNames: array[TDay] of string = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');

var
  hours: array[TDay] of Integer;
  d: TDay;
begin
  for d := Mon to Sun do
    hours[d] := 8;
  hours[Sat] := 0;
  hours[Sun] := 0;
  for d := Mon to Sun do
    WriteLn(DayNames[d], ': ', hours[d]);
end.

Constant and initialized arrays

PASCAL
const
  Primes: array[1..5] of Integer = (2, 3, 5, 7, 11);
var
  squares: array[0..4] of Integer = (0, 1, 4, 9, 16);

Multidimensional arrays

An array of arrays models tables and grids. Two spellings are equivalent:

PASCAL
var
  grid: array[1..3, 1..4] of Integer;       { 3 rows, 4 columns }
  same: array[1..3] of array[1..4] of Integer;
  r, c: Integer;
begin
  for r := 1 to 3 do
    for c := 1 to 4 do
      grid[r, c] := r * c;
  WriteLn(grid[2, 3]);                       { 6 }
end.

Memory is laid out row by row, so loop over the last index in the inner loop for best speed.

Dynamic arrays

A dynamic array has no fixed size in its declaration; you set the length at run time with SetLength. Indexes always run from 0 to Length - 1:

PASCAL
var
  data: array of Integer;
  i: Integer;
begin
  SetLength(data, 5);
  for i := 0 to High(data) do
    data[i] := i * i;
  WriteLn(Length(data));          { 5 }

  SetLength(data, 8);             { grow: new elements are zero, old values kept }
  data[7] := 99;

  SetLength(data, 0);             { frees the memory }
end.

Rules to remember:

  • Before SetLength the array is empty (Length = 0, the variable is nil).
  • Growing keeps existing values; shrinking drops the tail.
  • Dynamic arrays are reference counted and assignment copies the reference, not the data: after b := a, both names refer to the same elements. Use Copy(a) for an independent copy (or b := Copy(a, 0, Length(a))).
  • They are freed automatically when no variable refers to them. You never call Free.
  • A two-dimensional dynamic array: SetLength(m, rows, cols).
PASCAL
var
  a, b: array of Integer;
begin
  SetLength(a, 3);
  a[0] := 1;
  b := a;             { same array: b[0] is also 1 }
  b[0] := 5;
  WriteLn(a[0]);      { 5 }
  b := Copy(a);       { now independent }
  b[0] := 9;
  WriteLn(a[0]);      { still 5 }
end.

Delphi 10.4 and Free Pascal 3.2 also let you write array literals such as a := [3, 1, 2]; for dynamic arrays and use Insert/Delete helpers.

Open arrays and passing arrays

As seen in Parameters, a parameter declared array of T accepts static or dynamic arrays of any length. For a type you can name, declare it explicitly:

PASCAL
type
  TIntArray = array of Integer;

function Largest(const a: TIntArray): Integer;
var
  i: Integer;
begin
  Result := a[0];
  for i := 1 to High(a) do
    if a[i] > Result then
      Result := a[i];
end;

A first sorting example

Bubble sort repeatedly swaps neighbors that are out of order. It is slow for large data but short and visual:

PASCAL
procedure BubbleSort(var a: array of Integer);
var
  i, j, t: Integer;
begin
  for i := High(a) downto 1 do
    for j := 0 to i - 1 do
      if a[j] > a[j + 1] then
      begin
        t := a[j];
        a[j] := a[j + 1];
        a[j + 1] := t;
      end;
end;

In real programs use the generic sorting routines in Generics.Collections (Delphi) or fgl/Generics.Collections (Free Pascal).

Strings are close relatives

A string behaves like an array of characters (1-based). array[1..n] of Char is also valid, but you almost always want string. Chapter 7 reads files into arrays and strings.

Stand-ins in C

C arrays are zero-based and have a fixed size, but dynamic sizing is available with malloc and realloc. The programs are C.

C C stand-in: a table and a 1-based array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C C stand-in: dynamic array with SetLength and bubble sort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the first valid index of array of Integer (a dynamic array)?

    Dynamic arrays are always zero-based. Static arrays use whatever range you declare.
  2. 2. After b := a with two dynamic arrays, what happens when you change b[0]?

    Dynamic array assignment copies the reference. Use Copy for an independent copy.
  3. 3. Why use Low(a) and High(a) in loops?

    Hard-coded bounds break when the declaration changes; Low and High keep loops correct.
  4. 4. What does SetLength(data, 8) do to a dynamic array of length 5?

    Growing preserves existing elements; the new ones are initialized to zero.

Summary

  • Static arrays: array[low..high] of T, any ordinal index; copied by value.
  • Multidimensional arrays: array[r, c]; dynamic arrays: array of T, SetLength, zero-based, reference counted.
  • Use Low, High, Length; enable {$R+} to catch bad indexes while developing.
  • Open array parameters accept either kind.

Next: Records and Variant Records