Using Length () with multidimensional dynamic arrays in Delphi

I am using a multidimensional dynamic array in delphi and trying to figure this out:

I have 2 separate values ​​for the first index and the second index, which are completely separate from each other.

When new values ​​appear, I want to grow an array if this new value is outside of any boundary.

For new values ​​of x, y

I'm checking:

if Length(List) < (x + 1) then
   SetLength(List, x + 1);
if Length(List[0]) < (y + 1) then
   SetLength(List, Length(List), y + 1);

Is this the right way to do this, or is there a better way to expand the array as needed?

+3
source share
3 answers

I think you forgot to use the second index in the second dimension;

Your code should probably look like this:

if Length(List) < (x + 1) then
   SetLength(List, x + 1);
if Length(List[x]) < (y + 1) then
   SetLength(List[x], y + 1);

"x" .

:

, Delphi ( , AnsiString). - , , , - !

- - ..: ( , ).

, "" , , / SetLength().

+2

,

SetLength(List, Length(List), y + 1);
+4

@PatrickvL: , . , List [x]. (PatrickvL , .)

.

TestDimensions;

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  List: array of array of integer;

begin
  //set both dimensions
  SetLength(List, 3, 2);
  Writeln('X = ', Length(List), ', Y = ', Length(List[0])); //X = 3, Y = 2
  //set main dimension to 4, keep subdimension untouched
  SetLength(List, 4);
  Writeln('X = ', Length(List), ', Y = ', Length(List[0])); //X = 4, Y = 2
  //set subdimension to 3, keep main dimenstion untouched
  SetLength(List, Length(List), 3);
  Writeln('X = ', Length(List), ', Y = ', Length(List[0])); //X = 4, Y = 3
  //all List[0]..List[3] have 3 elements
  Writeln(Length(List[0]), Length(List[1]), Length(List[2]), Length(List[3])); //3333
  //you can change subdimension for each List[] vector
  SetLength(List[0], 1);
  SetLength(List[3], 7);
  //List is now a ragged array
  Writeln(Length(List[0]), Length(List[1]), Length(List[2]), Length(List[3])); //1337
  //this does not even compile because it tries to set dimension that does not exist!
//  SetLength(List[0], Length(List[0]), 12);
  Readln;
end.

Delphi (Structured Types, Arrays).

, ... . ,

type TMessageGrid = ;
var Msgs: TMessageGrid;

. , SetLength . , J - ,

SetLength (Msgs, I, J);

I-by-J, Msgs [0,0] .

, . SetLength, n . ,

var Ints: Integer,
SetLength (, 10);

Ints, . ( );

SetLength (Ints [2], 5);

Ints . ( ) - , Ints [2,4]: = 6.

( IntToStr, SysUtils) .

Var
  A: array of string array;
  I, J: Integer,
  start
    SetLength (A, 10);
    for I: = Low (A) - high (A) do
      start
        SetLength (A [I], I);
        for J: = Low (A [I]) to High (A [I]) do
          A [I, J]: = IntToStr (I) + ',' + IntToStr (J) + '';
      end;
  end;

+1
source

Source: https://habr.com/ru/post/1697818/


All Articles