Where does the "garbage" in the vector come from?

Good time of day.

I need to convert a two-dimensional array to a one-dimensional one. I did this in a simple, elementary loop and ... found that in the array, in addition to the matrix elements, some "left, garbage" values fall into the array. I output the matrix elements in ListBox. The "junk" elements come first, and the ones I need come at the end. What could possibly work wrong?

Code of the button that describes the algorithm:

procedure TForm2.Button5Click(Sender: TObject);
begin
  counter := 1;
  ListBox1.Clear;
  for i := 1 to n do
    for j := 1 to n do
    begin
      vec[counter] := a[i, j];
      ListBox1.Items.Add(inttostr(vec[counter]));
      counter := counter + 1;
    end;
end;
Author: Злой Шкальник, 2020-10-12

1 answers

You need to set a sufficient size for vec - n2 elements:

vec: array [1..n*n] of integer
 1
Author: MBo, 2020-10-12 18:12:41