本例是顺着 GetMem 的例子往下做的:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1;
implementation

{$R *.dfm}

Type
  TMyRec = record     {定义结构; 记住该结构的大小是 12 个字节}
    name: string[8];
    age : Word;       {虽然 Word 是 2 字节大小; 但因按 4 字节对齐, 它占用 4 字节}
  end;
  PMyRec = ^TMyRec;   {定义结构指针}

var
  pr: PMyRec;

procedure TForm1.FormCreate(Sender: TObject);
const
  str = '地址: %d; 姓名: %s';
begin
  {申请 3 个 TMyRec 结构大小的内存}
  //GetMem(pr, SizeOf(TMyRec) * 3);
  ReallocMem(pr, SizeOf(TMyRec) * 3); {这一句也可以用上一行代替}

  {赋值}
  pr.name := '张三';
  pr.age := 11;

  Inc(pr);
  pr.name := '李四';
  pr.age := 22;

  Inc(pr);
  pr.name := '王五';
  pr.age := 33;

  {显示三个结构的地址与信息; 地址应该是连续的(相间 12 字节)}
  Dec(pr, 2);
  ShowMessage(Format(str, [Integer(pr), pr.name])); {地址: 15278504; 姓名: 张三}
  Inc(pr);
  ShowMessage(Format(str, [Integer(pr), pr.name])); {地址: 15278516; 姓名: 李四}
  Inc(pr);
  ShowMessage(Format(str, [Integer(pr), pr.name])); {地址: 15278528; 姓名: 王五}

  {重新申请内存, 要 5 个结构大小, 并给 2 个新的结构赋值}
  Dec(pr, 2);
  ReallocMem(pr, SizeOf(TMyRec) * 5);

  Inc(pr, 3);
  pr.name := '马六';
  pr.age := 44;

  Inc(pr);
  pr.name := '孙七';
  pr.age := 55;

  {显示相关信息; 会发现地址虽然还是连续的, 但已经和上面不同!}
  Dec(pr, 4);
  ShowMessage(Format(str, [Integer(pr), pr.name])); {地址: 14875920; 姓名: 张三}
  Inc(pr);
  ShowMessage(Format(str, [Integer(pr), pr.name])); {地址: 14875932; 姓名: 李四}
  Inc(pr);
  ShowMessage(Format(str, [Integer(pr), pr.name])); {地址: 14875944; 姓名: 王五}
  Inc(pr);
  ShowMessage(Format(str, [Integer(pr), pr.name])); {地址: 14875956; 姓名: 马六}
  Inc(pr);
  ShowMessage(Format(str, [Integer(pr), pr.name])); {地址: 14875968; 姓名: 孙七}

  Dec(pr, 4);
  FreeMem(pr, SizeOf(TMyRec) * 5); {也可以用 FreeMem 清理 ReallocMem 申请的内存}
end;

end.

System 单元下的公用函数目录

posted on 2008-03-27 22:39  万一  阅读(4515)  评论(3编辑  收藏  举报