Jump to content
Jacek Laskowski

Dynamic arrays and copying

Recommended Posts

 

I create an array of arrays, then assign the data in whole rows (array).

 

Example code:

 

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

var
  lValues: array of TArray<Variant>;

procedure TestAddRowData();
var
  lRow : TArray<Variant>;
begin
  SetLength(lRow, 3);
  SetLength(lValues, 3);

  lRow[0] := 'one';
  lRow[1] := 1;
  lRow[2] := '1one';
  lValues[0] := lRow;

  lRow[0] := 'two';
  lRow[1] := 2;
  lRow[2] := '2two';
  lValues[1] := lRow;

  lRow[0] := 'three';
  lRow[1] := 3;
  lRow[2] := '3three';
  lValues[2] := lRow;
end;


begin
    TestAddRowData();
    Writeln(lValues[0, 0]);
    Writeln(lValues[0, 1]);
    Writeln(lValues[0, 2]);
    Writeln(lValues[1, 0]);
    Writeln(lValues[1, 1]);
    Writeln(lValues[1, 2]);
    Writeln(lValues[2, 0]);
    Writeln(lValues[2, 1]);
    Writeln(lValues[2, 2]);
    Readln;
end.

Results:

three
3
3three
three
3
3three
three
3
3three

 

I expected to get all the data according to their addition...

 

Isn't there a Copy on Write rule for arrays?

Share this post


Link to post

The copy on write rule is only for strings.

Arrays are reference counted and that's it.

If you need to copy the content of the array, you need to use the copy() function. It will create a new instance of your array.

 

Share this post


Link to post
procedure TestAddRowData();
begin
  lValues := [
    ['one', 1, '1one'],
    ['two', 2, '2two'],
    ['three', 3, '3three']
  ];

  // or
  SetLength(lValues, 3, 3);

  lValues[0,0] := 'one';
  lValues[0,1] := 1;
  lValues[0,2] := '1one';

  lValues[1,0] := 'two';
  lValues[1,1] := 2;
  lValues[1,2] := '2two';

  lValues[2,0] := 'three';
  lValues[2,1] := 3;
  lValues[2,2] := '3three';
end;

 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×