Wednesday, December 16, 2009

Understanding arrays

One of the most hard-to-understand thing for a beginner in programming(from my point of view) is the array.
If you're a "nub" in programming and arrays are making fun of you, then you should continue reading as I walk you to the bright side of arrays.
Consider a glass of milk as a element of a array and 2 glasses of milk as a array of milk glass, in Delphi code you can define as
// define a new type as record called TMilkGlass
type TMilkGlass = record
                // some info about the milk glass
                Quantity : integer;

// define the array of TMilkGlass defined above
type TArrayOfMilkGlass = array of TMilkGlass;
When you define a array of some type, you tell Delphi's compiler how much memory to allocate when the array size is increased(when you add a new element) or how much memory to free when array size is decreased(when you delete a element).
A way simpler example of the above example would be:
- the milk glass

- the array of milk glass

Seeing the above array of milk glasses, we can observe that we have 6 milk glasses we can define a array like so
type TArrayOfMilkGlass = array[0..5] of TMilkGlass;
When you define a new array of type and you DO NOT mention a range like in above example [0..5] this type of array is called "dynamic array", a array with range i.e. [0..5] is called "static array".
At this time your eyes should be opened(if not, keep trying, don't give up!), but remember:
- dynamic arrays: when you define a dynamic array you must set the length of the array before accessing a element, otherwise you will get a Access Violator :), use SetLength - in order to set the length of the array, Length - to get the length of the array, Low - to get the first element, High - to get the last element.
example of fooling around with a dynamic array
var x : array of integer;
     // allocate space in array for 50 integers
     SetLength(x, 50);
     // get the length of array
     // show as message the first element from array
     // show as message the last element from array
     // show as message the starting index of array
     // keeping in consideration that x could have
     // been defined as:
     // x: array[-5..20] of integer;
     // show as message the ending index of array
     // free allocated space for x
     SetLength(x, 0);
Note: that arrays that contain objects|classes, needs you to handle the creation and freeing of the objects, array will NOT create or free objects by itself.
- static arrays: Note: that you cannot set the length of a static array at runtime! this type of array is mostly used when you need to define a list of TYPE at design time that would hold some kind of data with a fixed size.
If you have any questions, don't hesitate to ask.
See also all post with array label.

No comments:

Post a Comment

Blogroll(General programming and Delphi feeds)