delphi指针问题

RBA*_*RBA 3 delphi pointers delphi-2006

我有以下代码正在运行,但我不理解它100%(请参阅代码中的注释):

unit Unit1;

interface

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

type
  TMyRec=record
    a:Integer;
    b:String;
  end;
  TRecArray=array of TMyRec;
  PRecArray = ^TRecArray;

  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
   v1:TRecArray;
   procedure Test(a:PRecArray);
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
 SetLength(v1,3);
 v1[0].b:='test1';//set the first value
 Test(PRecArray(v1));//call method to change the value assigned before
end;

procedure TForm1.Test(a: PRecArray);
begin
 ShowMessage(v1[0].b);//shows test1
 try
  a^[0].b:='test2' //this is raising an error...
 except

 end;
 PRecArray(@a)^[0].b:='test3';//this is working...
 ShowMessage(v1[0].b);//shows test3
end;

end.
Run Code Online (Sandbox Code Playgroud)

我不明白为什么'a ^ [0] .b:='test2'引发错误.

谢谢!

Ser*_*yuz 10

你的'Test'程序需要一个'PRecArray',但是你要传递一个'TRecArray'.试着把它称为

 Test(@v1);//call method to change the value assigned before
Run Code Online (Sandbox Code Playgroud)

将"TRecArray"类型化为'PRecArray'不会使其成为'PRecArray'.(注意:当然,你的'test3'会失败.)