Search code examples
pointersdelphirecordpascal

Delphi Records - creating a pointer to it


I'm trying to see how I can create a pointer to a simple record.

I have searched for similar topics before posting but it's quite confusing.

I create A & B of which are actual Records. I then have a variable C which I want to be just a 'pointer to this record'. I don't want C to store its own value but just a pointer to either A or B.
But whenever C is read/written to, it's actually being written to either A or B, whichever C is pointing to.

In other words, it's like a pointer to an Object, but I don't need an Object in my case.

Using Delphi 10.3 & 10.4 (if there's any difference), please highlight.

The code below results in Access Violation on first 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;

Solution

  • C should contain address of A, so make

    C := @A; 
    

    and the rest of code will work as needed.

    Also note that C.Field1 is implicit dereference, it really works as C^.Field1


    For now

    C^ := A;
    

    denotes assigning contents of A record to memory region addressed by C, but this memory is not allocated - that's why access violation occurs. (To allocate memory, you can make New(C), but this is not needed for your purposes)

    Also if you are going to actively use pointer to record, you can define type

    PMyRecord  =  ^TMyRecord;