[Lazarus] Pointer woes when trying to port a Delphi program

Bernd prof7bit at gmail.com
Sat Aug 25 14:42:43 CEST 2012


2012/8/24 brian <brian at meadows.pair.com>:

> Buttons[1]^ := FirstButton;

It is crashing because here you are dereferencing an uninitialized
pointer  Button[1] does not contain any reasonable value at this
moment, Button[1]^ therefore points to some random location and
Buton[1]^:= is trying to write something to that random memory
location and will therefore segfault.

But actually what you really want to do in a situation where you
initialize an array of pointers would be to write the *address* of
something *into* the array:

ArrayOfPointers[1] := @SomeThing;

But this also does not really make much sense in your scenario as
others have noted already, the variable FirstButton is of type TButton
and because TButton is a class this variable *is* something like a
pointer already (its holds a reference of a TButton instance, actually
internally it really is just a pointer). So you should just define
your array like this:

Type
 TBtnArray = Array [1..36] of TButton;

var
 Buttons: TBtnArray;

begin
  Buttons[1] := FirstButton;


If you look a the generated Assembly code you will see that it really
treats these TButton variables like pointers and the array is just an
array of Pointers, although you did not need to write any Pointer
syntax anywhere at all (most of the time when designing your data
structures wisely you don't need to use pointer syntax and even if you
are porting or interfacing with C++ code you can often (not always)
come up with equivalent Pascal code that greatly reduces the amount of
needed Pointer syntax, looking much more elegant and readable).




More information about the Lazarus mailing list