Examples Delphi

RICHARD'S DELPHI TIPS AND TRICKS
Last update October 1998
Passing Arrays As Parameters
In order to pass an array as a parameter to a function, we must pass it
as what is known as an 'open array' -that is, we must pass it as an array
that has no indication of size, as in 'array of Char' or array of Integer'
etc. Both the FORMAL declaration in the list of function headers (usually
at the top of the program declared as methods of a form object) AND the
actual parameters of the procedure or function must BOTH conform to this
rule.
One thing you need to be careful of is declaring arrays to be
tempArray: array[1..n] rather than tempArray: array[0..n] because while
you can do that it can create problems when doing things like
tempString := String(tempArray); (So restrict yourself to array[0..n])!
Here's an example from a real program:
const
chunkLen = 100;
type
TForm1 = class(TForm)
.
.
function EditLine(tempLine: array of Char; i: Integer): String;
end;
procedure CallingFunction;
var
srcChunk: array[0..chunkLen] of Char;
i: Integer;
tempString: String;
begin
{get text from somewhere and put it in srcChunk...}
srcChunk[i] := #0;
tempString := EditLine(srcChunk, i);
end;
function TForm1.EditLine(tempLine: array of Char; i: Integer): String;
{this function takes as a parameter a char array which is a single line
(aka 'chunk') of text. At this point, however, we may have 'part-words'
at the beginning and end of the line, so this routine strips away these
unwanted characters to produce lines that start and end with whole words.
The resulting 'edited' line is returned as a string...}
var
j, n: Integer;
tempArray: array[0..chunkLen] of Char;
tempString: String;
begin
{firstly go forward in the sourcefile 'chunk' until you get to a space...}
j := i;
i := 0;
while not(tempLine[i] = ' ') do
begin
Inc(i);
if (i >= j) then break;
end;
Inc(i);
n := 0;
{now put the whole of what remains into tempArray...}
while (i <= j) do
begin
tempArray[n] := tempLine[i];
Inc(i);
Inc(n);
end;
{and then backtrack from the END of temparray, until you get to a space,
placing a NULL character (#0) in the last 'non-space' position...}
while not(tempArray[n] = ' ') do
begin
Dec(n);
if (n <= 0) then break;
end;
tempArray[n] := #0;
tempString := string(tempArray);
Result := tempString;
end;
****************************************************************
AND YOU CAN'T RETURN AN ARRAY from A FUNCTION IN DELPHI, unfortunately
(unless you use some very unweildy and therefore possibly inadvisable
pointer syntax) so if you really need to return an array from a function
then the best bet might be to have the array as a global variable...