Difference between revisions of "Dynamic array"

From Lazarus wiki
Jump to navigationJump to search
m
Line 9: Line 9:
 
   <b>begin
 
   <b>begin
 
   ...
 
   ...
   </b> SetLength (MyVariable, ItsLength);
+
   </b> SetLength (MyVariable, ItsNewLength);
 
   ...
 
   ...
 
   <b>end</b>
 
   <b>end</b>
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.
+
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 before you can use the variable for the first time.  
  
The individual elements can be accessed by the same technique as the static arrays:
+
The individual elements can be accessed as usual:
 
   ...
 
   ...
 
   MyVariable[18] := 123;
 
   MyVariable[18] := 123;
Line 21: Line 21:
 
   ...
 
   ...
  
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.
+
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.
  
 
[[category:Pascal]]
 
[[category:Pascal]]

Revision as of 02:32, 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, ItsNewLength);
 ...
 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 before you can use the variable for the first time.

The individual elements can be accessed as usual:

 ...
 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.