Lección 18 · 18 de 20
Arrays dinámicos · Pascal
Use en Pascal arrays dinámicos que crecen y menguan con SetLength: un carrito de la compra con funciones para añadir productos y sumarlos.

Un array dinámico se declara sin tamaño, array of Double, y su tamaño se cambia mientras el programa se ejecuta con `SetLength`. Empieza vacío: nil es un array dinámico sin elementos.
Add hace crecer el carrito: SetLength(list, Length(list) + 1) añade un hueco al final y list[High(list)] := value lo rellena. El parámetro es var porque el procedimiento cambia el array de quien lo llama.
A diferencia de los estáticos, los arrays dinámicos siempre empiezan en el índice 0: con tres productos, los índices van de 0 a High(cart), que vale 2, mientras que Length da 3.
Sum recibe el array con const, sin copiarlo, y lo recorre con for x in list. Para pasar un array dinámico como parámetro conviene definir antes su tipo, aquí TPrices.
SetLength(cart, 2) también encoge el array: el último producto desaparece. No hace falta liberar la memoria: Free Pascal lo hace solo cuando el array deja de usarse.
Código · 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.Salida · 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
Para recordar
array of Tes un array sin tamaño fijo.SetLength(a, n)lo hace crecer o encoger.- Los índices van de
0aHigh(a). - La memoria se libera sola.
Ejercicio
Escriba una función MostExpensive(const list: TPrices): Integer que devuelva el índice del producto más caro, y escriba su posición y su precio.