Retrieving an Element of an Array: Difference between revisions

m
m (→‎{{header|C++}}: lang tag)
Line 170:
 
A Static array definition:
<lang pascal> foo : array[1..10] of integer; { The base index is ONE }</lang>
The base index can be freely chosen:
<lang pascal> foo: array[7 .. 16] of integer; { The base index is 7 }</lang>
Indeed, the "1 .. 10" resp. "7 .. 16" are actually ''types'': they are integer subrange types. Arrays can also be indexed by enumeration types or enumeration subrange types:
<lang pascal> type
rainbowcolor = (red, orange, yellow, green, blue, violet);
var
Line 183:
i := foo[red]; { allowed indices are red, orange, yellow, green, blue, violet }
i := bar[green]; { allowed indices are yellow, green, blue }
end;</lang>
A Dynamic Array type in Delphi:
<lang delphi> foo : array of integer ; // The base index is ZERO</lang>
An "old school" dynamic array in the various flavors of pascal
<lang delphi> foo : array[0..0] of integer; // The base index is ZERO</lang>
A dynamic array in Extended Pascal:
<lang pascal> type
intarray(n: integer) = array[1 .. n] of integer; { base index 1 }
var
Line 197:
i := foo[2];
dispose(foo); { get rid of the array }
end;</lang>
In the case of the static array, the compiler generates the code to allocate the required memory to hold 10 integers.
 
In the Delphi style ---dynamic--- array you must set its length:
<lang delphi> SetLength(foo,10); // this array will no hold 10 integers</lang>
In the "old school" style of dynamic arrays, you created a point to the zero length declaration and then allocated memory to it with GetMem
<lang pascal> pFoo : ^Foo ;
Foo : array[0..0] of integer ;</lang>
 
All arrays are accessed the same way regardless of declaration method.
 
<lang pascal> i : integer ;
i := foo[n] ;</lang>
where n is the array index who's base is either 1 or 0 depending on how it was declared.