Recent

Author Topic: about procedures / dyn. arrays / setlength  (Read 3436 times)

guardian991

  • Newbie
  • Posts: 1
about procedures / dyn. arrays / setlength
« on: May 27, 2017, 07:20:58 pm »
Hi. Please take a look at the following code. I got a "type mismatch" error .. can someone explain why it behaves so,  is the workaround okay ?
Code: Pascal  [Select][+][-]
  1. Type dynStrArray = ARRAY OF AnsiString;
  2.  
  3. Procedure Test1( VAR test : dynStrArray  );
  4. const elements = 100;
  5. Begin
  6.      setlength( test , elements );
  7. end;
  8.  
  9. Procedure Test2( VAR test : Array OF AnsiString );
  10. const elements = 100;
  11. Begin
  12.      setlength( test, elements );
  13. end;
  14.  
  15. BEGIN
  16.  
  17. END.

sky_khan

  • Guest
Re: about procedures / dyn. arrays / setlength
« Reply #1 on: May 27, 2017, 08:13:37 pm »
I think compiler takes test2's argument as open array parameter so it does not allow modifying it. test1 is ok.
See: https://www.freepascal.org/docs-html/ref/refsu68.html

molly

  • Hero Member
  • *****
  • Posts: 2330
Re: about procedures / dyn. arrays / setlength
« Reply #2 on: May 27, 2017, 08:24:06 pm »
As skyhan wrote, an open array is something else then a dynamic array.

Setlength is a bit more explicit in its documentation and mentions that var a must be of "DynArrayType", which (as you showed correctly in your first routine) has to be declared specifically as type.

Your second routine is indeed using an open array as parameter.

Zoran

  • Hero Member
  • *****
  • Posts: 1828
    • http://wiki.lazarus.freepascal.org/User:Zoran
Re: about procedures / dyn. arrays / setlength
« Reply #3 on: May 27, 2017, 09:11:23 pm »
In Pascal, dynamic arrays and open array parameters are two different things, but they are declared with same syntax. Therefore, people are often confused.

This is well explained in this article, find the section named "Confusion" and read it.

Thaddy

  • Hero Member
  • *****
  • Posts: 14169
  • Probably until I exterminate Putin.
Re: about procedures / dyn. arrays / setlength
« Reply #4 on: May 28, 2017, 07:25:17 am »
It is still a bit more confusing in trunk...because of implicit dynamic array constructors...
This is now legal:
Code: Pascal  [Select][+][-]
  1. var
  2.   a:array of integer;
  3. begin
  4. a: = [1,2,3,4,5]; // inferred size, dynamic array
  5. end.
  6.  
But indeed, Rudy's write-up is still relevant. Note the above will ONLY work in trunk.
« Last Edit: May 28, 2017, 07:28:37 am by Thaddy »
Specialize a type, not a var.

 

TinyPortal © 2005-2018