user2375049
user2375049

Reputation: 350

dynamic array as type in delphi/pascal object

I have a unit in which there are multiple variables that has to be same sized vectors.

However I do not know the length of this array before i parse the file.

So I want to have a dynamic array that is "global" for the whole unit and then i can

The code below shows the issue as well as the solution I have now. The solution I have now is to assign a maximum value to be the length of the array.

unit xyz;
interface 

uses
abc

const
maxval=50;

type
vectorofdouble = [1...maxval] of double;  // I want to change this to dynamic array

type
  T_xyz = object

  public
    NP: integer;
  private
    var1: vectorofdouble;        
    var2: vectorofdouble;        
   public
    number: integer;       
    var3: vectorofdouble; 

  private
    procedure Create();
    function func1(etc): integer;
  public
    procedure ReadFile(const FileName, inputs: string);
  end;

implementation
procedure T_xyz.ReadFile();
////////
Read(F,np)
  //SetLength(vectorofdouble, np) // DOES NOT WORK
  for i := 0 to maxval // I DONT WANT TO LOOP UP TO MAXVAL
  begin
    var1[i] := 0
  end;

procedure T_xyz.func1(etc);
////////
do stuff
  for i := 0 to maxval // I DONT WANT TO LOOP UP TO MAXVAL
  begin
    var2[i] := 0
  end;
end;

end.

Upvotes: 0

Views: 987

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596176

You want to use a dynamic array instead of a fixed-length array. You do that by using

array of <Type>

instead of

array[<Low>..<High>] of <Type>

Then SetLength() will work, but you need to pass it a dynamic array variable instead of a type.

Try this:

unit xyz;

interface

uses
  abc;

type
  vectorofdouble = array of double;

type
  T_xyz = object
  public
    NP: integer;
  private
    var1: vectorofdouble;
    var2: vectorofdouble;
  public
    number: integer;
    var3: vectorofdouble;
  private
    procedure Create();
    function func1(etc): integer;
  public
    procedure ReadFile(const FileName, inputs: string);
  end;

implementation

procedure T_xyz.ReadFile();
var
  i: integer;
begin
  Read(F, NP);
  SetLength(var1, NP);
  for i := 0 to NP-1 do
  begin
    var1[i] := 0;
  end;
end;

procedure T_xyz.func1(etc);
begin
  for i := Low(var2) to High(var2) do
  begin
    var2[i] := 0;
  end;
end;

end.

Upvotes: 3

David Heffernan
David Heffernan

Reputation: 612954

You must pass the array to SetLength rather than the type. So instead of

SetLength(vectorofdouble, np)

you must use

SetLength(var1, np)

Upvotes: -1

Related Questions