[fpc-pascal] pointer magic

cobines cobines at gmail.com
Tue Apr 27 13:45:24 CEST 2010


2010/4/27 spir ☣ <denis.spir at gmail.com>:
> -1- untyped pointer allocation
> In case of an untyped pointer, I read the compiler considers the target'size is 1 byte. There certainly is an operation to allocate memory for the target according to an existing piece of data. Something like
>    data := something
>    new(p,data);
>    // Either p points to data where it was
>    // or a new memory area is silently reserved,
>    // data copied there, and p holds its address.

New(p) doesn't work for untyped pointers, you have to use GetMem,
FreeMem for example, where you give the amount of memory in bytes to
allocate. After allocating memory you have to set/copy the data
yourself.

Target size of untyped pointer is 1 byte for pointer arithmetics. For example:

var
  p: Pointer;
  pl: ^Node;
begin
  p := someNode.next;
  pl := someNode.next;
  p := p + 1;   // + 1 byte
  pl := pl + 1;  // + SizeOf(Node) bytes
end;

> -2- reflexive pointing
> The following works, but I do not understand how.
...
> The issue is: ^endNode holding a pointer to endNode, how is this kind of infinite self-referencing loop resolved by the compiler, at definition time?

The compiler doesn't care what value is written there, as long as type
is compatible.

> PS: How else terminate a linked list in Pascal? (I must put something in the .next field of the last actual node, and this thing must be a List, ie a node pointer.)

Put 'nil', and then while traversing the list when you encounter that
pointer to next node is nil then you are at the end of the list.

--
cobines



More information about the fpc-pascal mailing list