首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

全局Tlist输出结构体异常

2012-08-03 
全局Tlist输出结构体错误请教大虾们个问题:在程序中我定义一个结构体MyRecord和一个全局的TlisttypeMyRec

全局Tlist输出结构体错误
请教大虾们个问题:在程序中我定义一个结构体MyRecord和一个全局的Tlist;
  type
MyRecord = record
Code: String;
Name: string;
Age: Integer;
end;

var
 list:TList;
在窗体的OnCreate事件中初始化list list:=TList.create;
在一个button1的单击事件中给list赋值:
procedure TForm1.Button1Click(Sender: TObject);
var
  col,rol:MyRecord;
  i:Integer;
begin
  col.Code:='1';
  col.Name:='张三';
  col.Age:=22;

  rol.Code:='2';
  rol.Name:='李四';
  rol.Age:=23;

  list.Add(@col);
  list.Add(@rol);
end;

然后点击另一个button2,输出list中的值就会出错,提示access violation at address,请大虾们帮我看看是什么原因:
procedure TForm1.Button2Click(Sender: TObject);
var
  i:Integer;
begin
  for i:=0 to list.Count-1 do
  begin
  ShowMessage(MyRecord((list.Items[i])^).name);
  end;
end;


[解决办法]
type
PMyRecord = ^MyRecord;
MyRecord = record
Code: String;
Name: string;
Age: Integer;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
col,rol:PMyRecord;
i:Integer;
begin
New(col);
col.Code:='1';
col.Name:='张三';
col.Age:=22;

New(rol);
rol.Code:='2';
rol.Name:='李四';
rol.Age:=23;

list.Add(col);
list.Add(rol);
end;


procedure TForm1.Button2Click(Sender: TObject);
var
i:Integer;
begin
for i:=0 to list.Count-1 do
begin
ShowMessage(PMyRecord(list.Items[i])^.name);
end;
end;


热点排行