How to pass a single element of an array to a procedure?

Example

procedure TForm1.ButtonClick(Sender: TObject);
var x:integer;
begin
   SetLength(MyArray,10)
   for x:=0 to 9 do FillWithRandomNumbers(MyArray[x]);
end;

Procedure FillWithRandomNumbers(var MyArray: Array of double);
begin
  MyArray:=Random; //<-I have no idea what to do here :(
end;

As you can see, I am trying to pass one element to a procedure in order to perform some task in the specified cell of the array. For example, the FillWithRandomNumbers procedure should accept MyArray [2] and fill this cell with a random number.

+4
source share
1 answer

You want to pass one element of an array, but your procedure expects a full array. To directly answer your real question, your procedure should be defined as:

Procedure FillWithRandomNumber(var Value: double);  
begin
  Value:= Random;
end;

procedure TForm1.ButtonClick(Sender: TObject);
var x:integer;
begin
   SetLength(MyArray,10)
   for x:=0 to 9 do FillWithRandomNumber(MyArray[x]);
end;

Or you could do it like this:

procedure TForm1.ButtonClick(Sender: TObject);
begin
   SetLength(MyArray, 10);
   FillWithRandomNumbers(MyArray);
end;

Procedure FillWithRandomNumbers(var SomeArray: Array of double);
var
  X: Integer;
begin
  for X := Low(SomeArray) to High(SomeArray) do begin
    SomeArray[X] := Random;
  end;
end;

Or, to be even simpler, just don't use the procedure at all:

procedure TForm1.ButtonClick(Sender: TObject);
var
  X: Integer;
begin
  SetLength(MyArray, 10);
  for X := 0 to High(Array) do begin
    MyArray[X]:= Random;
  end;
end;
+4
source

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


All Articles