Delphi32.com - Home!
| Home/News | Downloads | Forums | D32 Magazine | Resources | Info and Facts |  
 
 Resizing an array


How can I resize an array?   

    You cannot resize a non-dynamic array in Pascal. You can create and resize a dynamically created array. To do this, you must create the dynamic array, turn range checking off, and access the array members via a variable only, or you will recieve runtime and compile time errors. Since you will access the array through a pointer variable, you can dynamically resize the array by creating a new array in memory, copy all the valid elements of the original array to the new array, free the memory for the original array, and assign the new array's pointer back to the original array pointer. Example:

    type
      TSomeArrayElement = integer;
      PSomeArray = ^TSomeArray;
      TSomeArray = array[0..0] of TSomeArrayElement;

    procedure CreateArray(var TheArray : PSomeArray; NumElements : longint); begin GetMem(TheArray, sizeof(TSomeArrayElement) * NumElements); end;

    procedure FreeArray(var TheArray : PSomeArray; NumElements : longint); begin FreeMem(TheArray, sizeof(TSomeArrayElement) * NumElements); end;

    procedure ReSizeArray(var TheArray : PSomeArray; OldNumElements : longint; NewNumElements : longint); var TheNewArray : PSomeArray; begin GetMem(TheNewArray, sizeof(TSomeArrayElement) * NewNumElements); if NewNumElements > OldNumElements then Move(TheArray^, TheNewArray^, OldNumElements * sizeof(TSomeArrayElement)) else Move(TheArray^, TheNewArray^, NewNumElements * sizeof(TSomeArrayElement)); FreeMem(TheArray, sizeof(TSomeArrayElement) * OldNumElements); TheArray := TheNewArray; end;

    procedure TForm .Button Click(Sender: TObject); var p : PSomeArray; i : integer; begin {$IFOPT R+} {$DEFINE CKRANGE} {$R-} {$ENDIF}

    CreateArray(p, 200); for i := 0 to 99 do p^[i] := i; ResizeArray(p, 200, 400); for i := 0 to 399 do p^[i] := i; ResizeArray(p, 400, 50); for i := 0 to 49 do p^[i] := i; FreeArray(p, 50);

    {$IFDEF CKRANGE} {$UNDEF CKRANGE} {$R+} {$ENDIF} end;

     



  << Previous Faq     Complete List     Next Faq >>  



 
 Hits/month  2,500,000+ 
 Downloads
 (Since May 2000)
 7,393,709 
 Total Files  6,023 
 Forum msgs  7,670 
 Articles/FAQs  70+/900+ 
Kylix
Tips n Tricks
FAQs
Knowledge Base
Bug Listings
Articles
Books
Newsgroups
Links
Submissions
Testimonials
Advertising
Contact Us
About Us
Search Amazon:
Top Selling Software at Amazon

| Home/News | Downloads | Forums | Resources | Info and Facts | Testimonials |
  Site Search:
 


Comments/Problems: Webmaster@delphi32.com
Copyright © 1998-2006, Delphi32.com. All rights reserved.
Terms of Use