3

I have a problem with Delphi.

I wrote a function like this:

function MyFunction(arr: array of AnsiString): Boolean;
begin
  //code here
end;

And now, when I pass an array of AnsiString directly into function, like this, everything works perfectly:

MyFunction(['one', 'two', 'three']);

But, when I try to store this array like this:

var arr: array of AnsiString;

procedure MyProcedure;
begin
  arr[0] := ['one', 'two', 'three'];
  MyFunction(arr[0]);
end;

There is a mismatch error.

I'm a beginner with Delphi, but this is really confusing.

4
  • You might take a look at this article: rvelthuis.de/articles/articles-openarr.html Commented Dec 21, 2017 at 19:45
  • 1
    Why are you even using AnsiString? Commented Dec 21, 2017 at 21:56
  • @DavidHeffernan is this important? For array of string there is the same issue. Commented Dec 22, 2017 at 9:55
  • It will become important when your program starts receiving non ASCII data Commented Dec 22, 2017 at 10:08

1 Answer 1

10

Your second example is not functionally identical to the fist example.

The first example is fine. The function takes an open array as an input parameter, and you are constructing a fixed array of strings directly in that parameter, which is perfectly fine. Any array type can be passed to an open array parameter.

In the second example, you are declaring a dynamic array of strings, but you are not allocating any memory for the array, and you are trying to assign its first element (which is a single string) to point at a fixed array of strings. And then you are trying to pass that element (again, a single string) where an array is expected. That is why the code fails to compile.

The correct way to write your procedure would like more like this:

procedure MyProcedure;
var
  arr: array of AnsiString;
begin
  SetLength(arr, 3);
  arr[0] := 'one';
  arr[1] := 'two';
  arr[2] := 'three';
  MyFunction(arr);
end;

Alternatively:

procedure MyProcedure;
var
  arr: array of AnsiString;
begin
  arr := ['one', 'two', 'three'];
  MyFunction(arr);
end;

Alternatively:

type
  TAnsiStringArray = array of AnsiString;

procedure MyProcedure;
var
  arr: TAnsiStringArray;
begin
  arr := TAnsiStringArray.Create('one', 'two', 'three');
  MyFunction(arr);
end;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.