0

I wrote a function that gives me the length of a dynamic array by converting it to string and asking length(trim(string));

function arraylength(a: array of char): integer;
var i: integer;
s: string;
begin
    for i:=0 to high(a) do
  begin
  s[i] := a[i-1];
    Result := length(trim(s));
  end;
end;

In my main program i read text into a string, convert it to array

procedure TForm1.Button2Click(Sender: TObject);
var i: integer;
begin
  for i:=0 to length(sString) do
  begin
    cChar[i] := sString[i];
  end;
end;

and do:

ShowMessage(IntToStr(arraylength(cChar)));

I get the error as stated in the title.

2
  • 3
    The rest of your code is very broken. Arrays' base index is zero. Strings' base address is one. Neither strings nor arrays contain anything until you call SetLength. You should check the length of s outside the loop; otherwise, you should get a warning that the function might not return a value. Any why are you converting your string to an array anyway, if the next thing you do is stuff it back into a string? Commented Aug 5, 2009 at 13:34
  • 1
    Look into StrLen() and similar functions. Why aren't you using PChar in the first place? Commented Aug 5, 2009 at 13:41

1 Answer 1

4

When passing arrays to procedures and functions in delphi you should declare them as a separate type. Thus:

type
  MyArray =  array of char; 

and then

function arraylength(a: MyArray ): integer;

BTW: why aren't you using built-in functions like Length() ? In Delphi2009 type string is unicode string, so Length returns Length in characters, not in bytes.

Sign up to request clarification or add additional context in comments.

2 Comments

Im not using it because in that case I have a dynamic array and length(cChar) returns something bigger than the actual count of characters in the array due to the dynamic allocation of space. A function that gives me the ACTUAL count of characters would be highly appreciated.
You mean you have array of say 20 elements, buy you only use 15 at the moment?

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.