How do I declare an array whose length is given at runtime?

I need to declare an array with user defined size. This array is inside a rather large program, and changing the list can be quite problematic.

Now my array is declared like this:

Buffer: array[0..myCostant * 2] of Byte;

      

and myCostant

, as he says, a constant already defined. Now I need to use the variable, getting something like this:

Buffer: array[0..myVar * 2] of Byte;

      

but i cant use variables inside array definition.

How can I solve this without changing my array in something else? This variable is bounded at the top, so I can declare an array with this maximum size and shrink it with another command?

+3


source to share


1 answer


You have to use dynamic arrays :

var
  Buffer: array of Byte;

begin
  SetLength(Buffer, myVar*2 + 1);

      

Alternatively, you can use a static array of known upper-bound length and write the current "significant" length of the array in a variable, for example CurrentLength

.

Then you can replace for example



for i := 0 to Length(Buffer) - 1 do
  SomethingWith(Buffer[i]);

      

by

for i := 0 to CurrentLength - 1 do
  SomethingWith(Buffer[i]);

      

+10


source







All Articles