unit Unit1;interfaceuses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls;type
TValue = Record
str1: string;
Int: integer;
str2: string;
str3: string;
End;
PValue = ^TValue; TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;var
Form1: TForm1;
List: TList;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);
Var
i, j: integer;
TreeNode, ValueNode: TTreeNode;
ArrayValue: Array Of PValue;
begin
SetLength(ArrayValue,4);
For i := 0 To 4 Do
Begin
GetMem(ArrayValue[i],SizeOf(PValue));
ArrayValue[i]^.str1 := 'aaa';
ArrayValue[i]^.str2 := 'bbb';//在这里出错,帮帮我查一下为什么?谢谢!
ArrayValue[i]^.str3 := 'ccc';
End;
IF Assigned(List) Then List.Destroy;
IF Not Assigned(ArrayValue) Then Raise Exception.Create('Null of ArrayValue');
List := TList.Create;
List.Add(ArrayValue);
ShowMessage('The ArrayValue has Add into List Item');
end;end.帮帮我查一下为什么?谢谢!
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls;type
TValue = Record
str1: string;
Int: integer;
str2: string;
str3: string;
End;
PValue = ^TValue; TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;var
Form1: TForm1;
List: TList;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);
Var
i, j: integer;
TreeNode, ValueNode: TTreeNode;
ArrayValue: Array Of PValue;
begin
SetLength(ArrayValue,4);
For i := 0 To 4 Do
Begin
GetMem(ArrayValue[i],SizeOf(PValue));
ArrayValue[i]^.str1 := 'aaa';
ArrayValue[i]^.str2 := 'bbb';//在这里出错,帮帮我查一下为什么?谢谢!
ArrayValue[i]^.str3 := 'ccc';
End;
IF Assigned(List) Then List.Destroy;
IF Not Assigned(ArrayValue) Then Raise Exception.Create('Null of ArrayValue');
List := TList.Create;
List.Add(ArrayValue);
ShowMessage('The ArrayValue has Add into List Item');
end;end.帮帮我查一下为什么?谢谢!
For i := 0 To 4 Do 改成 0 To 3
试一下看看吧,好像是越界了。因为动态数组是0基数组。
For i := 0 To 3 Do
...
ArrayValue: Array Of TValue;
begin
SetLength(ArrayValue,4);
For i := 0 To 3 Do
Begin
ArrayValue[i].str1 := 'aaa';
ArrayValue[i].str2 := 'bbb';
ArrayValue[i].str3 := 'ccc';
End;
...
end;
应该是SizeOf(TValue)吧。
For i := 0 To 4 Do
Begin
GetMem(ArrayValue[i],SizeOf(PValue));/////////这里错误。
ArrayValue[i]^.str1 := 'aaa';
ArrayValue[i]^.str2 := 'bbb';
ArrayValue[i]^.str3 := 'ccc';
End;
/////////////////
sizeof(PValue)值是4,这里GetMem(ArrayValue[i],sizeof(PValue))其实给ArrayValue申请了4个字节的空间,后面赋值,到str2的时候,aaa+bbb>4,所以溢出了。
不是PValue
Begin
// GetMem(ArrayValue[i],SizeOf(PValue));
--------------------->>>>>>>>>>>>>>>
new(ArrayValue[i]);////ArrayValue[i]是一个指针
ArrayValue[i]^.str1 := 'aaa';
ArrayValue[i]^.str2 := 'bbb';
ArrayValue[i]^.str3 := 'ccc';
End;