Sunday, October 11, 2009

Get dynamic array limits

Knowing the start and end index of an array is important, specially if you have a dynamic array.
A static array is a array of type with defined number of elements, that means that you know it's start and end index.
Note The number of elements in a static array cannot be changed!
Example of a static array
type TMyStaticArray = array[0..5] of integer;
A dynamic array is a array of type with dynamic number of elements, this means that at any time you can change it size using the SetLength procedure.
Note The number of elements in a static array can be changed using the SetLength procedure, example
type TMyDynamicArray = array of integer;

procedure ChangeMyDynamicArraySize;
var myDynamicArray : TMyDynamicArray;
    currentLength : Integer;
     (* get the current number of elements from array *)
     currentLength := Length(myDynamicArray);
     (* increase it's number of elements by 1 *)
     SetLength(myDynamicArray, currentLength + 1);
     (* now our dynamic array has 1 more element *)
Now back to the subject of this post, as you can see above, the number of elements of a dynamic array is unknown at compile time but it can drastically change at runtime, getting the start of a dynamic array is easy you just have to use the Low function and to get the end of it you use High or Length functions, Length function can be used on strings also, because a string is a dynamic array of char.
type TMyDynamicArray = array of integer;

procedure getArrayLimits;
var myDynamicArray : TMyDynamicArray;
    endIndex : Integer;
     startIndex := Low(myDynamicArray);
     endIndex := High(myDynamicArray);
     (* as I said above you can also use the Length function *)
     (* to get the end index so... *)
     endIndex := Length(myDynamicArray) - 1;
    (* Warning, when using the Length function you must *)
    (* decrement it's return value by 1 otherwise you *)
    (* will get an AV(Access Violation) *)

No comments:

Post a Comment

Blogroll(General programming and Delphi feeds)