[fpc-pascal] Pointer question

Michael Van Canneyt michael at freepascal.org
Fri Aug 11 07:37:38 CEST 2023



On Thu, 10 Aug 2023, Hairy Pixels via fpc-pascal wrote:

>
>
>> On Aug 10, 2023, at 4:23 PM, Hairy Pixels <genericptr at gmail.com> wrote:
>>
>> // 4) subscript (inc and dereference in one step)
>> v := i[1];
>>
>>
>> #4 was not  in the list for example so I wonder what others exist.
>
> I found another one in the typinfo.pp unit. What does,
>
> 1) taking the address of a type (@TAlignCheck) yield and
> 2) what does dereferencing nil yield?
>
> Both I've never seen before until now.
>
> type
> TAlignCheck = record
>   b : byte;
>   w : word;
> end;
> var
> p: pointer;
> begin
> p := @TAlignCheck(nil^).w;
> end;

This is a very dirty trick to get the offset of a field in a record.

Note that you're not dereferencing a type but a variable of type TAlignCheck located
at memory address zero. The address of w (this is what the expression is
doing) is then the offset of w in the record.

It's probably more clear if you write it as
  p := @(TAlignCheck(nil^).w);

Michael.


More information about the fpc-pascal mailing list