How to allocate a matrix dynamically in Pascal

1 Answer

0 votes
program DynamicMatrix;

type
  PRow = ^TRow;
  TRow = array of Integer;
  PMatrix = ^TMatrix;
  TMatrix = array of PRow;

var
  Matrix: PMatrix;
  Rows, Columns, i, j, TotalCells: Integer;

begin
  // Define matrix dimensions dynamically 
  Rows := 3;;
  Columns := 4;

  // Allocate memory for matrix 
  New(Matrix);
  SetLength(Matrix^, Rows);
  for i := 0 to Rows - 1 do
  begin
    New(Matrix^[i]);
    SetLength(Matrix^[i]^, Columns);
  end;

  // Fill matrix with sample values 
  for i := 0 to Rows - 1 do
    for j := 0 to Columns - 1 do
      Matrix^[i]^[j] := i * Columns + j;

  // Calculate total cells 
  TotalCells := Rows * Columns;

  WriteLn('Matrix size: ', Rows, ' rows x ', Columns, ' columns');
  WriteLn('Total Cells: ', TotalCells);

  // Print matrix 
  for i := 0 to Rows - 1 do
  begin
    for j := 0 to Columns - 1 do
      Write(Matrix^[i]^[j]:4);
    WriteLn;
  end;

  // Free memory 
  for i := 0 to Rows - 1 do
    Dispose(Matrix^[i]);
  Dispose(Matrix);
end.



(*
run:

Matrix size: 3 rows x 4 columns
Total Cells: 12
   0   1   2   3
   4   5   6   7
   8   9  10  11

*)

 



answered Oct 2 by avibootz
edited Oct 2 by avibootz
...