動的配列のコピー
2701 ワード
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
type
TArr = array of Int64; { , }
var
arr1,arr2: TArr; { }
p: Pointer; { }
{ }
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
for i := 0 to 1000 - 1 do
begin
SetLength(arr1, Length(arr1)+1);
arr1[High(arr1)] := i * 2;
end;
{ }
ShowMessage(IntToStr(arr1[9])); {18}
end;
{ }
procedure TForm1.Button1Click(Sender: TObject);
var
size: Cardinal;
begin
size := Length(arr1) * SizeOf(arr1[0]); { }
GetMem(p, size); { }
CopyMemory(p, arr1, size); { }
arr2 := TArr(p); { }
{ }
ShowMessage(IntToStr(arr2[9])); {18}
end;
end.
配列要素が構造であると仮定し、もう一度テストします.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
type
TRec = record
str: string;
int: Integer;
end;
TArr = array of TRec;
var
arr1,arr2: TArr;
p: Pointer;
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
for i := 0 to 1000 - 1 do
begin
SetLength(arr1, Length(arr1)+1);
arr1[High(arr1)].str := IntToStr(i);
arr1[High(arr1)].int := i * 2;
end;
ShowMessageFmt('%s,%d',[arr1[9].str, arr1[9].int]); {9,18}
end;
procedure TForm1.Button1Click(Sender: TObject);
var
size: Cardinal;
begin
size := Length(arr1) * SizeOf(arr1[0]);
GetMem(p, size);
CopyMemory(p, arr1, size);
arr2 := TArr(p);
ShowMessageFmt('%s,%d',[arr2[9].str, arr2[9].int]); {9,18}
end;
end.