Reputation: 350
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
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
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