动态数组的使用
//例1:
var
StrArr: array of String; //动态数组定义时不与维数
begin
SetLength(StrArr,6,',','); //分配6个元素位置: 0-5
StrArr[0] := '万一'; //动态数组的下界是 0
ShowMessage(StrArr[0],',','); //分配空间后和静态数组一样使用
StrArr := nil; //一般没必要手动释放, 动态数组离开作用域会自释放
end;
--------------------------------------------------------------------------------
//例2. 动态数组的引用:
var
Arr1,Arr2: array of Integer;
a: array[0..1] of Integer;
begin
SetLength(Arr1,6,',',');
Arr1[5] := 100;
Arr2 := Arr1; //Arr2 引用了 Arr1
ShowMessage(IntToStr(Arr2[5]),',','); //100
ShowMessage(IntToStr(Length(Arr2)),',','); //当然 Arr2 维数也会是 6
ShowMessage(IntToStr(SizeOf(Arr1)),',','); //4, 其实动态数组是个指针
ShowMessage(IntToStr(SizeOf(Arr2)),',','); //4
Arr2[5] := 99; //现在它们指向同一个数组, 改变这个就是改变那个
ShowMessage(IntToStr(Arr1[5]),',','); //99
Arr1 := nil; //释放其中一个指针, 数组继续存在
ShowMessage(IntToStr(Arr2[5]),',','); //99
end;
--------------------------------------------------------------------------------
//例3. 数组 Copy <1>:
var
Arr1,Arr2: array of Integer;
begin
SetLength(Arr1,6,',',');
Arr1[5] := 100;
Arr2 := Copy(Arr1,',','); //数组 Copy
Arr2[5] := 99; //改变 Arr2 不再影响 Arr1
ShowMessage(IntToStr(Arr1[5]-Arr2[5]),',','); //1
SetLength(Arr1,7,',',');
ShowMessage(IntToStr(Length(Arr1)),',','); //7
ShowMessage(IntToStr(Length(Arr2)),',','); //6, 没有一点牵扯了
end;
--------------------------------------------------------------------------------
//例4. 数组 Copy <2>:
var
Arr1,Arr2: array of Integer;
i: Integer;
begin
SetLength(Arr1,6,',',');
for i := Low(Arr1) to High(Arr1) do //给每个元素赋值
Arr1[i] := i+1;
Arr2 := Copy(Arr1,1,3,',','); //只 Copy 第2..4个元素
ShowMessage(IntToStr(Arr1[1]),',','); //2, 现在 Arr2[0] 和 Arr1[1] 的值是一样的
ShowMessage(IntToStr(Arr2[0]),',','); //2
ShowMessage(IntToStr(Length(Arr1)),',','); //6, 维数肯定不一样了
ShowMessage(IntToStr(Length(Arr2)),',','); //3
end;
--------------------------------------------------------------------------------
//例5. 动态多维数组:
var
Arr: array of array of Integer; //定义多维数组
begin
SetLength(Arr,5,5,',','); //分配空间
Arr[0,3] := 100; //赋值
ShowMessage(IntToStr(Arr[0,3]),',','); //取值
end;
--------------------------------------------------------------------------------
//例6. 另类建立:
var
Arr: array of Integer;
begin
Arr := varArrayCreate([0,3],varInteger,',',');
ShowMessage(IntToStr(Length(Arr)),',','); //4
Arr := VarArrayOf([1,2,3,4],',',');
ShowMessage(IntToStr(Arr[0]),',','); //1
{这是给变体数组使用的,可能会有效率问题}
end;
关键字词: