Difference between revisions of "Dynamic array"

From Free Pascal wiki
Jump to navigationJump to search
Line 1: Line 1:
An dynamic array is a type that in very similar to the [[array|array]] type, but allows more flexibility since the size of this array does not need to be known before the actual execution of the program. The declaration part is just as simple as the static array:   
+
The dynamic array type is very similar to the [[array|array]] type, but it allows more flexibility since the number of elements does not need to be known until the program execution.
 +
 
 +
The declaration part is just as simple as the [[array|array]] type:   
 
   <b>var</b>
 
   <b>var</b>
 
   ...
 
   ...
 
   MyVariable : <b>array of</b> type;
 
   MyVariable : <b>array of</b> type;
 
   ...
 
   ...
Its dimensions can be set or modified whenever needed during the execution of the program by using the statement:
+
The number of elements can be set or modified whenever needed during the execution of the program by using the statement:
 
   <b>begin
 
   <b>begin
 
   ...
 
   ...
Line 10: Line 12:
 
   ...
 
   ...
 
   <b>end</b>
 
   <b>end</b>
You must include one or more statements in your program in order to create, expand, or truncate your array.
+
You can put as many </b>SetLength<b> statements as you want in your program in order to expand, or truncate an array, but you must put at least one statement before you can use the variable.
 
 
The array is located on the heap by the dynamic memory allocator and is freed on the program or procedure exit.
 
  
 
The individual elements can be accessed by the same technique as the static arrays:
 
The individual elements can be accessed by the same technique as the static arrays:

Revision as of 02:27, 16 January 2010

The dynamic array type is very similar to the array type, but it allows more flexibility since the number of elements does not need to be known until the program execution.

The declaration part is just as simple as the array type:

 var
 ...
 MyVariable : array of type;
 ...

The number of elements can be set or modified whenever needed during the execution of the program by using the statement:

 begin
 ...
  SetLength (MyVariable, ItsLength);
 ...
 end

You can put as many SetLength statements as you want in your program in order to expand, or truncate an array, but you must put at least one statement before you can use the variable.

The individual elements can be accessed by the same technique as the static arrays:

 ...
 MyVariable[18] := 123;
 ...
 MyOtherVariable := Myvariable[0];
 ...

The index of a dynamic array is zero based, ie. it MUST be whittin the range from 0 to (Length-1). It is not possible to change this to a ONE based system.