How to clone a two-dimensional array in Pascal

2 Answers

0 votes
program Clone2DArray;

type
  T2DArray = array of array of Integer;

var
  arr2D, ClonedArray: T2DArray;
  i, j, Rows, Cols: Integer;

begin
  Rows := 3;
  Cols := 4;

  // Set the length of the original array
  SetLength(arr2D, Rows, Cols);

  // Initialize the original array with some values
  for i := 0 to Rows - 1 do
    for j := 0 to Cols - 1 do
      arr2D[i][j] := i * Cols + j;

  // Set the length of the cloned array
  SetLength(ClonedArray, Rows, Cols);

  // Copy the elements from the original array to the cloned array
  for i := 0 to Rows - 1 do
    for j := 0 to Cols - 1 do
      ClonedArray[i][j] := arr2D[i][j];

  for i := 0 to Rows - 1 do
  begin
    for j := 0 to Cols - 1 do
      Write(ClonedArray[i][j]:3);
    Writeln;
  end;
end.



(*
run:

  0  1  2  3
  4  5  6  7
  8  9 10 11

*)

 



answered Mar 8, 2025 by avibootz
0 votes
program Clone2DArray;

type
  T2DArray = array of array of Integer;

var
  arr2D, ClonedArray: T2DArray;
  i, j, Rows, Cols: Integer;

function CloneArray2D(const source: T2DArray): T2DArray;
var
  rows, cols, i, j: Integer;
  result: T2DArray;
begin
  rows := Length(source);
  if rows = 0 then
  begin
    SetLength(result, 0);
    CloneArray2D := result;
    Exit;
  end;
  cols := Length(source[0]);
  SetLength(result, rows, cols);

  for i := 0 to rows - 1 do
    for j := 0 to cols - 1 do
      result[i][j] := source[i][j];

  CloneArray2D := result;
end;

begin
  Rows := 3;
  Cols := 4;

  // Set the length of the original array
  SetLength(arr2D, Rows, Cols);

  // Initialize the original array with some values
  for i := 0 to Rows - 1 do
    for j := 0 to Cols - 1 do
      arr2D[i][j] := i * Cols + j;

  // Clone the array using the function
  ClonedArray := CloneArray2D(arr2D);

  for i := 0 to Rows - 1 do
  begin
    for j := 0 to Cols - 1 do
      Write(ClonedArray[i][j]:3);
    Writeln;
  end;
end.



(*
run:

  0  1  2  3
  4  5  6  7
  8  9 10 11

*)

 



answered Mar 8, 2025 by avibootz
...