www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Returning Arrays from Functions

reply Samwise <mggmugginsmc gmail.com> writes:
I've done a whole bunch of looking around, and I don't see any 
mention of returning a dynamic array from a function. When I try 
it though, it just returns the .length value of the array, rather 
than the contents of the array. Does anyone know why this is, and 
what I can do to make it behave the way I want it to?
Jan 18 2017
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
What code do you have now?
Jan 18 2017
parent reply Samwise <mggmugginsmc gmail.com> writes:
On Wednesday, 18 January 2017 at 22:37:25 UTC, Adam D. Ruppe 
wrote:
 What code do you have now?
This is the basic function. It takes all those boolean arguments and does things depending on them, and then takes any extra args that getopt didn't parse and reads them into numbs. That code works fine, because I write it out after that's done but before I pass it back to main(). ulong[] getInp (bool help, bool file, bool inp, string[] args) { //... writeln(numbs); return numbs; } Here is what I've got in main (Minus some more stuff). Right now it's just printing out what it gets, but it will use other functions to apply operations to numbs later. int main(string[] args) { ulong[] numbs; //... numbs[] = getInp(help, file, inp, args); writeln(numbs); return 0; } That prints out an empty array. If I initialize one element, (numbs[0] ~= 0;) then it prints out numbs.length. Really kinda weird... Thanks, ~Sam
Jan 18 2017
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Wednesday, 18 January 2017 at 22:51:17 UTC, Samwise wrote:
 	numbs[] = getInp(help, file, inp, args);
This is wrong, try just `numbs = getImp(...);` numbs[] = xxx will copy stuff into the existing array, which is empty right now. You want to jut keep the slice the function passes back.
Jan 18 2017
parent Samwise <mggmugginsmc gmail.com> writes:
On Wednesday, 18 January 2017 at 23:09:15 UTC, Adam D. Ruppe 
wrote:
 On Wednesday, 18 January 2017 at 22:51:17 UTC, Samwise wrote:
 	numbs[] = getInp(help, file, inp, args);
This is wrong, try just `numbs = getImp(...);` numbs[] = xxx will copy stuff into the existing array, which is empty right now. You want to jut keep the slice the function passes back.
Huh. I thought I tried that. I guess I didn't, since it worked like a charm. Thanks loads. ~Sam
Jan 18 2017