Search code examples
pascalfreepascallazarus

Defining an unknown amount of variables


A long time ago a got stuck with a problem: if I need to make a small program that use variables, how do you define and unknown amout of variables?.

I.E, if you have a program that ask user to input a number, then the number user input is the numer of variables needed in program. In Java or VB is easy solve this because you can define variables as you need them (on the go), but pascal makes you declare them BEFORE main program code start, so you can't use this trick.

I was thinking on a multi dimensional array, but I think that is a poor way to fix this, because if you define less "squares" than you need you get short and if you define more than you actually are gonna use then you are gonna waste memory...

So, how do you define an unknown amount of variables?


Solution

  • You can dynamically resize the array using SetLength

    Type 
      TByteArray = Array of Byte;
    
    Var
      Data : TByteArray
      NewSize : Integer;
    Begin
      Write('Enter the number of bytes you require: ');
      ReadLn(NewSize)
      SetLength(Data, NewSize);
      ...
    End;
    

    Excuse any syntax errors, I have not used Pascal in more that 20 years. What a great language!