【发布时间】:2020-11-12 04:42:41
【问题描述】:
我正在尝试了解如何创建指向简单记录的指针。
我在发帖前搜索过类似的主题,但很混乱。
我创建了 A 和 B,其中是实际记录。
然后我有一个变量 C ,我想它只是一个“指向该记录的指针”。
我不希望 C 存储它自己的值,而只是一个指向 A 或 B 的指针。
但是每当 C 被读/写时,
它实际上被写入 A 或 B,无论 C 指向哪个。
换句话说,它就像一个指向对象的指针,但在我的情况下不需要对象。
使用 Delphi 10.3 和 10.4(如果有任何区别),请突出显示。
下面的代码导致第一个 ShowMessage 出现访问冲突。
procedure TForm1.Button2Click(Sender: TObject);
type
TMyRecord = record
Field1 : integer;
end;
var
A : TMyRecord;
B : TMyRecord;
C : ^TMyRecord; // how to declare this as a pointer?
begin
A.Field1 := 1;
B.Field1 := 2;
C^ := A; // psuedo code to point to A
A.Field1 := 3;
showmessage( C^.Field1.ToString ); // result is 3
C.Field1 := 4;
showmessage( A.Field1.ToString ); // result is 4
C^ := B; // psuedo code to point to A
C.Field1 := 5;
showmessage( B.Field1.ToString ); // result is 5
// anything to free here to avoid memory loss?
end;
【问题讨论】:
标签: pointers delphi record pascal