{多維動態數組}
procedure TForm1.BitBtn1Click(Sender: TObject);
var
Arr: array of array of array of Integer; {定義一個三維動態數組}
i,j,k,ic,jc,kc: Integer;
begin
Memo1.Lines.Clear;
SetLength(Arr, 2,3,4);
{獲取各維的維數}
ic := Length(Arr);
jc := Length(Arr[0]);
kc := Length(Arr[0][0]);
{賦值}
for i := 0 to ic - 1 do
for j := 0 to jc - 1 do
for k := 0 to kc - 1 do
Arr[i][j][k] := Random(100);
{取值}
Memo1.Clear;
for i := 0 to ic - 1 do
for j := 0 to jc - 1 do
for k := 0 to kc - 1 do
Memo1.Lines.Add(Format('Arr[%d][%d][%d] = %d', [i, j, k, Arr[i][j][k]]));
end;
{多維動態數組指針}
procedure TForm1.BitBtn2Click(Sender: TObject);
Type
TMyArr = array of array of array of Integer; {定義一個三維動態數組類型}
var
PArr: ^TMyArr; {動態數組指針變量}
i,j,k,ic,jc,kc: Integer;
begin
Memo1.Lines.Clear;
{用做維數的變量}
ic := 2;
jc := 3;
kc := 4;
{分配內存; 按說動態數組還須要 8 個管理字節, 我不知道 Delphi 是怎麼協調的}
GetMem(PArr, ic * jc * kc * SizeOf(Integer));
{設置數組}
SetLength(PArr^, ic,jc,kc);
{賦值}
for i := 0 to ic - 1 do
for j := 0 to jc - 1 do
for k := 0 to kc - 1 do
PArr^[i][j][k] := Random(100);
{取值}
Memo1.Clear;
for i := 0 to ic - 1 do
for j := 0 to jc - 1 do
for k := 0 to kc - 1 do
Memo1.Lines.Add(Format('Arr[%d][%d][%d] = %d', [i, j, k, PArr^[i][j][k]]));
//Memo1.Lines.Add(Format('Arr[%d][%d][%d] = %d', [i, j, k, TMyArr(PArr)[i][j][k]]));
{按理說這種訪問方法也對,但是這中方法在編譯的時候能通的過去,在運行的就報錯了}
{本身分配的內存要負責釋放}
FreeMem(PArr);
end;
procedure TForm1.Button1Click(Sender: TObject);
type
TArr = array[0..10] of Integer;
var
arr: ^TArr;
i:Integer;
begin
New(arr);
{這裏面就有個問題了,New()這函數是有來建立一個新指針,在delphi裏面指針保存的是地址,也就是說Arr 裏面保存的是地址碼,並無分配內存,但是爲何Arr^[i]卻還可以賦值呢?}
{賦值}
for i := 0 to 10 do
Arr^[i]:=i*i;
for i := 0 to 10 do
Memo1.Lines.Add(Format('Arr[%d] = %d', [i, Arr^[i]]));
Dispose(arr);
{這個Dispose釋放的是指針,也就是說把Arr保存的地址值清爲零,那麼用來保存數據的內存地址是怎麼釋放的?} end;