To declare multidimensional
dynamic arrays, use iterated array of ... constructions. For example,
type
TMessageGrid = array of array of string;
var Msgs:
TMessageGrid;
declares a two-dimensional array of
strings. To instantiate this array, call SetLength with two integer
arguments. For example, if I and J are integer-valued variables,
SetLength(Msgs,I,J);
allocates an I-by-J array, and Msgs[0,0]
denotes an element of that array.
You can create multidimensional
dynamic arrays that are not rectangular. The first step is to call SetLength,
passing it parameters for the first n dimensions of the array. For example,
var Ints:
array of array of Integer;
SetLength(Ints,10);
allocates ten rows for Ints but no
columns. Later, you can allocate the columns one at a time (giving them
different lengths); for example
SetLength(Ints[2], 5);
makes the third column of Ints five
integers long. At this point (even if the other columns haven’t been allocated)
you can assign values to the third column, for example, Ints[2,4] := 6.
The following example uses dynamic
arrays (and the IntToStr function declared in the SysUtils unit)
to create a triangular matrix of strings.
var
A : array of array of string;
I, J : Integer;
begin
SetLength(A, 10);
for I := Low(A) to High(A) do
begin
SetLength(A[I], I);
for J := Low(A[I]) to High(A[I]) do
A[I,J] := IntToStr(I) + ',' +
IntToStr(J) + ' ';
end;
end;
要声明多维动态数组,需要迭代使用array
of ... 结构。例如,
type
TMessageGrid = array of array of string;
var Msgs:
TMessageGrid;
声明了一个二维动态数组。要初始化该数组,需要调用标准过程SetLength并使用两个整数参数。例如,如果 I 和
J 是整数值变量,那么
SetLength(Msgs,I,J);
分配了一个 I x J 的二维数组,Msgs[0, 0]表示数组中的一个元素。
也可以创建非矩阵(上面调用SetLength之后的Msgs就是一个矩阵)的动态数组。首先,调用SetLength,将数组的第一个维数n作为参数。例如,
var Ints:
array of array of Integer;
SetLength(Ints,10);
这里为二维数组Ints分配了10行但没有任何行。然后,可以一次对一列分配行(可以指定不同的长度);例如
SetLength(Ints[2], 5);
这里为Ints第3列指定了5个整数的长度。执行该语句后,可以对第3列赋值,如Ints[2, 4] := 6。(尽管此时其他的列可能还没有被分配。)
下面的例子用动态数组(以及SysUtils单元中声明的IntToStr函数)创建了一个三角矩阵,数组的基类型是串。
var
A : array of array of string;
I, J : Integer;
begin
SetLength(A, 10);
for I := Low(A) to High(A) do
begin
SetLength(A[I], I);
for J := Low(A[I]) to High(A[I]) do
A[I,J] := IntToStr(I) + ',' +
IntToStr(J) + ' ';
end;
end;
编者注
判定动态数组相等的唯一依据就是二者是否引用相同的数组。下面的例子说明了动态数组相等的情况:
var
A, B: array of string;
begin
SetLength(A, 5);
B := A;
if A = B then //此时
A = B 返回 True
ShowMessage('A = B');
A[0] := 'Hello';
B[0] := 'World'; //与前一行语句改变的数组索引是相同的,执行后串 'Hello' 被覆盖
ShowMessage(A[0]); //将显示
'World',因为此时A与B是相等的
end;