Returning dynamic array from the function

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 14 10:08:42 PDT 2014


On Saturday, 14 June 2014 at 14:02:52 UTC, Marco Cosentino wrote:
> Hi,
> I'm new to D and stumbled upon this very interesting discussion.
> My question now is:
> can you provide an example of how to return a collection of
> homogeneous elements whose size is not known at compile time 
> (for
> wich you would normally use a dynamic array) from a function?

     int[] foo() {
         int[] data = [1,2,3,4];    // create new array on the heap
         data ~= [5,6,7,8];         // append some data
         return data;
     }

The problem with the OP's code was not per se that he returned a 
slice, but that he took this slice from a fixed-length local 
array. The example above doesn't do that, and is therefore safe.


More information about the Digitalmars-d-learn mailing list