[lazarus] More of a FPC question but... dynamic arrays

Andrew Johnson aj_genius at hotmail.com
Fri Oct 18 15:38:14 EDT 2002


On 18 Oct 2002 13:25:20 -0500
"Tony Maro" <tonym at nlisc.com> wrote :
>
>On Sun, 2002-09-29 at 20:44, Andrew Johnson wrote:
>
> > var
> >   myarray : ^TObject;
> > begin
> >   ...//do stuff
> >   reallocmem(myarray, 4*SizeOf(TObject));//allocmem to handle 4 objects
> >   myarray[2] := thisobject;//set the 3 entry
> >   ...//do stuff.
> >   reallocmem(myarray, 0);//free memory
> > end;
> >
> > you simply use reallocmem in place of setlength, and multiply the length 
>by
> > the sizeof the type it contains.. at one point I actually created 
>wrappers
> > arround this to make more like Delphi dynamic arrays..but its been 
>awhile so
> > I do not know if I still have it. essentially though you should be able 
>to
> > port a lot of code with ease. by doing some sort of wrappers.. etc.
> >
> > Andrew
>
>Andrew (and others):
>
>I've successfully been using the above to manage arrays of records, but
>I finally tried to do objects this way and it won't work.  Here's the
>code snippett:
>
>procedure TFrmMain.PrintChecks;
>var
>    MyPrints: ^TChkTransaction; // array of transactions to print
>begin
>      writeln('Reallocating memory');
>      reallocmem(MyPrints, 0);
>      writeln('Zeroed.');
>end;
>
>Notice, I define a pointer and then attempt to make sure that the array
>is zero length to begin with (actually I added this just because I was
>testing why it crashed when I tried to set it the first time.)
>
>It access violations before the writeln('Zeroed.') is executed.
>
>At this point, I can't think of any reason it would cause a crash.  All
>I have is a pointer and I attempt to reallocate the memory for it...
>
>It crashes on reallocmem regardless of the size I specify:
>reallocmem(MyPrints, 0)
>and
>reallocmem(MyPrints,(2 * sizeof(TChkTransaction)))
>both result in a crash.  Am I doing something wrong?

Not exactly.. Basically you are dealing with a Pointer to a Pointer, if you 
were using ^Pointer or PPointer you would get the same results. I do not 
know why this make a difference, but it does. Basically this means you need 
to initialize the variable first with

new(MyPrints);

and finalize when done with

dispose(MyPrints);

Or use a pointer and type cast every time, which is clumsy, so I suggest you 
do it this way.

Andrew

_________________________________________________________________
Internet access plans that fit your lifestyle -- join MSN. 
http://resourcecenter.msn.com/access/plans/default.asp






More information about the Lazarus mailing list