Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi Passing Dynamic array of Records to function

I have a Dynamc array of Records and I wish to pass one of the items in the array to a function by reference

So for example one of the array items - AArray[1].arecorditem is a string of 6 characters String[6]

the function would be -

function dosomething(var AStringVal:string):Integer;

So I would execute

Aresult:= dosomething(AArray[1].arecorditem);

however when I try to compile I get the Error Type of actual and formal var parameters must be identical.

Is this possible to do or should I assign the array item to a string and then pass the string to the function.

Thanks

Colin

like image 301
colin Avatar asked Dec 27 '22 09:12

colin


2 Answers

Your question title and the actual question are not the same, so I'll give you an overview of both subjects.

You need to define an Array Type

TMyRecord = record
  Field1: String
  Field2: String
end;

TMyRecordArray = Array of TMyRecord

function DoSomething(const ARecordArray: TMyRecordArray): Integer;

This is if you want to pass an entire dynamic array of items to the function. If you just want to pass one item, you'd define the function like this:

function DoSomething(const ARecord: TMyRecord): Integer;

Now, if you want to pass the value of Field1 to the function, you would have to define the function as:

function DoSomething(const AField: String): Integer;

You cannot define the parameter as varor you'll end up with the error you're getting!

Additional:

As others have been saying, if you're using a fixed-length String for the field, you need to define it as a Type just as I have demonstrated above for TMyRecordArray.

TString6 = String[6];

Use that Type both for your Field, and your function Parameter.

like image 196
LaKraven Avatar answered Jan 10 '23 19:01

LaKraven


You'll have to create a type:

    type
      TName = string[80];

So you can call your function this way:

    function doSomething(var name: TName): Integer;
    begin
        ...
        ...
        ...
    end;  

Working Example

program HelloWorld;

type
  TName = string[80];

type
  TCustomer = record
    name : Name;
    age : byte;
  end;

procedure qwerty(var name: TName);
begin
  name := 'doSomething';
end;

var
  customers : array[1..3] of TCustomer;
  b : Byte;
begin

  with customers[1] do
  begin
    name := 'qwerty';
    age := 17;
  end;

  with customers[2] do
  begin
    name := 'poiuy';
    age := 18;
  end;

  writeln(customers[1].name);

  qwerty(customers[1].name);
  writeln(customers[1].name);

  Readln(b);
end.
like image 31
Eder Avatar answered Jan 10 '23 20:01

Eder