Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to resize an array in Pascal

1 Answer

0 votes
program DynamicArrayDemo;

type
  PIntArray = ^TIntArray;
  TIntArray = array[1..1] of Integer;  // Placeholder for dynamic allocation 

function AllocateArray(Size: Word): PIntArray;
var
  Arr: PIntArray;
begin
  GetMem(Arr, Size * SizeOf(Integer));
  if Arr = nil then
  begin
    WriteLn('malloc error');
    Halt(1);
  end;
  AllocateArray := Arr;
end;

function ResizeArray(Arr: PIntArray; OldSize, NewSize: Word): PIntArray;
var
  Tmp: PIntArray;
  I: Integer;
begin
  GetMem(Tmp, NewSize * SizeOf(Integer));
  if Tmp = nil then
  begin
    FreeMem(Arr, OldSize * SizeOf(Integer));
    WriteLn('realloc error');
    Halt(1);
  end;

  // Copy old data 
  for I := 1 to OldSize do
    Tmp^[I] := Arr^[I];

  // Initialize new elements to 0 
  for I := OldSize + 1 to NewSize do
    Tmp^[I] := 0;

  FreeMem(Arr, OldSize * SizeOf(Integer));
  ResizeArray := Tmp;
end;

procedure PrintArray(Arr: PIntArray; Size: Word);
var
  I: Integer;
begin
  for I := 1 to Size do
    WriteLn(Arr^[I]);
end;

var
  Arr: PIntArray;

begin
  Arr := AllocateArray(3);
  Arr^[1] := 10;
  Arr^[2] := 20;
  Arr^[3] := 30;

  PrintArray(Arr, 3);

  Arr := ResizeArray(Arr, 3, 5);

  WriteLn;
  WriteLn('after realloc');
  PrintArray(Arr, 5);

  Arr^[4] := 40;
  Arr^[5] := 50;

  WriteLn;
  WriteLn('after realloc & set new data');
  PrintArray(Arr, 5);

  FreeMem(Arr, 5 * SizeOf(Integer));
end.



(*
run:

10
20
30

after realloc
10
20
30
0
0

after realloc & set new data
10
20
30
40
50

*)

 



answered Oct 14, 2025 by avibootz
edited Oct 18, 2025 by avibootz
...