Step 1 of 5 · Reading · ~1 min
Learn
Records 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;
WriteLn(Length(nums)); { 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]);
Growing and shrinking — on this course's compiler (FPC 3.0.4), SetLength is the whole API:
SetLength(nums, Length(nums) + 1); { append: make room ... }
nums[High(nums)] := 42; { ... then fill the new last slot }
SetLength(nums, 2); { shrink: indices 0 and 1 survive,
everything past index 1 is gone }
FPC 3.2 later added Insert(value, nums, index) and Delete(nums, index, count) for dynamic arrays. On 3.0.4 those names resolve to the string versions and the compiler rejects the call, so stay with SetLength here.
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
Up nextPointersPointers and Sets
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…