Lesson 18 · 18 of 20
Dynamic arrays · Pascal
Use Pascal dynamic arrays that grow and shrink with SetLength: a shopping cart with routines to add items and total them up.

A dynamic array is declared without a size, array of Double, and resized while the program runs with `SetLength`. It starts empty: nil is a dynamic array with no elements.
Add grows the cart: SetLength(list, Length(list) + 1) adds a slot at the end and list[High(list)] := value fills it. The parameter is var because the procedure changes the caller's array.
Unlike static arrays, dynamic arrays always start at index 0: with three items, the indexes run from 0 to High(cart), which is 2, while Length gives 3.
Sum takes the array as const, without copying it, and walks through it with for x in list. To pass a dynamic array as a parameter, it is best to define its type first, here TPrices.
SetLength(cart, 2) also shrinks the array: the last item disappears. There is no need to free the memory: Free Pascal does it on its own once the array is no longer used.
Code · main.pas
program main;type TPrices = array of Double;procedure Add(var list: TPrices; value: Double);begin SetLength(list, Length(list) + 1); list[High(list)] := value;end;function Sum(const list: TPrices): Double;var x: Double;begin Result := 0; for x in list do Result := Result + x;end;var cart: TPrices; i: Integer;begin cart := nil; // nil: an empty dynamic array, with 0 items Add(cart, 2.50); Add(cart, 0.99); Add(cart, 4.75); for i := 0 to High(cart) do // index 0 is the first WriteLn('Item ', i, ': ', cart[i]:5:2); WriteLn('Total: ', Sum(cart):0:2, ' (', Length(cart), ' items)'); SetLength(cart, 2); // shrinking drops the last item WriteLn('Without the last one: ', Sum(cart):0:2);end.Output · fpc main.pas && ./main
Item 0: 2.50 Item 1: 0.99 Item 2: 4.75 Total: 8.24 (3 items) Without the last one: 3.49
Key points
array of Tis an array with no fixed size.SetLength(a, n)grows or shrinks it.- Indexes run from
0toHigh(a). - The memory is freed automatically.
Exercise
Write a MostExpensive(const list: TPrices): Integer function that returns the index of the most expensive item, and print its position and price.