zoukankan      html  css  js  c++  java
  • 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 单元下的公用函数目录

  • 相关阅读:
    Xshell 跳板机快速登录脚本按钮
    (一)angularjs5 环境搭建
    Myeclipse 内存溢出解决方法
    php 代码放到服务器上验证码不好用
    表格里面的input在底部
    Smarty忽略大括号
    php富友表单提交接口对接
    php富友接口对接http请求
    js去掉html标签
    删除的时候提示是否删除
  • 原文地址:https://www.cnblogs.com/del/p/1126180.html
Copyright © 2011-2022 走看看