[fpc-pascal] Schema Types

Jonas Maebe jonas.maebe at elis.ugent.be
Mon Dec 22 11:53:08 CET 2008


On 15 Dec 2008, at 21:29, Kevan Hashemi wrote:

> Dear FPC,
>
>> fancy:=new(fancy_type); // or something similar, I usually use  
>> GetMem not New
>> SetLength(fancy.first, 10, 20);
>> SetLength(fancy.second, 10, 20);
>> SetLength(fancy.third, 300);
>
> Nice. I see how it works. Thank you very much (Felipe and Florian)  
> for your answers. I'll try porting some code to FPC.

One important different to keep in mind between dynamic arrays and  
regular arrays (including those defined using schema types): dynamic  
arrays are reference counted and copies are always shallow copies.  
This means that in this code:

var
   a, b: array of real;
begin
   setlength(a,10);
   b:=a;
   a[5]:=1.0;
end.

at the end, b[5] will also be 1.0. To make a deep copy, use the  
following code after assignment:

setlength(b,length(b));

Note that this will only make the "first" level unique. I.e., if you  
have:

var
   a, b: array of array of real;
begin
   setlength(a,10,10);
   b:=a;
   setlength(b,length(b));
   a[5][5]:=1.0;
   writeln(b[5][5]);
end.

then this will still print 1.0. I don't think there is an easier way  
to make a full deep copy than using a loop to iteratively call  
setlength on all sub-arrays as well:

var
   a, b: array of array of real;
   i: longint;
begin
   setlength(a,10,10);
   b:=a;
   setlength(b,length(b));
   for i:=0 to high(b) do
    setlength(b[i],length(b[i]));
   a[5][5]:=1.0;
   writeln(b[5][5]);
end.



Jonas



More information about the fpc-pascal mailing list