System.ReallocMem - 重新申请内存

本例是顺着 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 单元下的公用函数目录

转载于:https://www.cnblogs.com/del/archive/2008/03/27/1126180.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值