当前位置: 首页 > 工具软件 > Free Pascal > 使用案例 >

Free pascal 指针处理

胡泓
2023-12-01
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.
 类似资料: