Skip to content
Dynamic Arrays
step 1/5

Reading — step 1 of 5

Learn

~1 min readRecords and Arrays

Pascal has two array kinds:

Static arrays — size fixed at compile time:

var
    nums: array[1..10] of integer;
    matrix: array[1..3, 1..3] of integer;
begin
    nums[5] := 42;
end.

Dynamic arrays (FPC/Delphi extension) — sized at runtime with SetLength:

var
    nums: array of integer;
begin
    SetLength(nums, 10);
    nums[0] := 42;
    Length(nums)             // returns 10
    SetLength(nums, 20);     // grow
    SetLength(nums, 5);      // shrink
end.

Dynamic arrays are 0-indexed. Use Length() for size.

Iteration:

for i := 0 to Length(nums) - 1 do
    WriteLn(nums[i]);

for i := Low(nums) to High(nums) do   // works for both static and dynamic
    WriteLn(nums[i]);

Array operations:

// Append (FPC 3.x):
Insert(value, nums, Length(nums));   // append
Delete(nums, i, count);              // remove

Open-array parameters — accept any size:

function Sum(a: array of integer): integer;
var i: integer;
begin
    Result := 0;
    for i := Low(a) to High(a) do
        Result := Result + a[i];
end;

// Caller:
WriteLn(Sum([1, 2, 3, 4, 5]));   // array constructor

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…