Free pascal 指针处理

TList.Add() 参数是一个 Pointer, 下面是一个如何将 Integer 值处理为 Pointer的. 

copy from :    https://forum.lazarus.freepascal.org/index.php?topic=22905.0

type
  pinteger=^integer;
var
  aList:TList;
  pi:pinteger;
  i:integer;
begin
  aList:=TList.Create;

  for i:=0 to 9 do
  begin
    New(pi);
    pi^:=i;
    aList.Add(pi);
  end;

  for i:=0 to aList.Count-1 do
    writeln(pinteger(aList[i])^);

  //take care about self created items
  for i:=aList.Count-1 downto 0 do
    Dispose(pinteger(aList[i]));

  aList.Clear;
  aList.Free;
end.

 

使用自定义对象, 比直接使用Pointer更简单.

type
  TTest=class
    Value:integer;
  end;

var
  aList:TList;
  aTest:TTest;
  i:integer;
begin
  aList:=TList.Create;

  for i:=0 to 9 do
  begin
    aTest:=TTest.Create;
    aTest.Value:=i;
    aList.Add(aTest);
  end;

  for i:=0 to aList.Count-1 do
    writeln(TTest(aList[i]).Value);

  //take care about self created items
  for i:=aList.Count-1 downto 0 do
    TTest(aList[i]).Free;

  aList.Clear;
  aList.Free;
end.

 

posted @ 2020-11-03 23:02  harrychinese  阅读(242)  评论(0编辑  收藏  举报