[fpc-pascal] Pointer question

Tomas Hajny xhajt03 at hajny.biz
Thu Aug 10 00:37:55 CEST 2023

On August 10, 2023 at 0:06:57 +0200, Hairy Pixels via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
>> On Aug 9, 2023, at 2:54 PM, Tomas Hajny via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
>>> 1) what does "i := x - x;" do and what is it's purpose and why doesn't "x + x" work the same?
>> Pointer subtraction is a reverse operation to adding a number to a pointer; the result of the subtraction is the offset between the two pointers.
>Is that different than decrementing the pointer?
>What would an offset between two pointers be used for? Is the offset even a memory address or just a number of bytes? If you had an example usage that would be interesting to see.

No, the offset is not a memory address but just a number of bytes (which is also the reason why you cannot add the pointers together, but you can add a number to a pointer. As an example, you could use this operation to find out the exact alignment of fields within a record (to check whether there's some padding inserted between them) - e.g. if you aren't sure what alignment directive was used for compiling a unit declaring the structure, or to understand the compiler behaviour for a particuler alignment directive..

>>> 2) I've used pointer equality of course but what does "x > p" do and what is its purpose?
>> Relative position between the two locations in memory? As an example, it may be used to check whether a particular pointer points to a location between the start and the end of an allocated memory block (obviously, you'd need two comparisons for that).
>I guess that makes sense if a memory address with a higher value is always after an address with a lower value. Is that assumption always true?

I believe that this is indeed guaranteed (at least as long as linear pointers are concerned, but Pascal pointer is IMHO always linear - as opposed to a farpointer using a segmented model or a combination of a selector and an offset.


More information about the fpc-pascal mailing list