Returning dynamic array from the function?

SuperPrower superprower at somedomain.org
Sat Sep 8 09:46:28 UTC 2018


On Saturday, 8 September 2018 at 09:36:21 UTC, rikki cattermole 
wrote:
> We're going to need to see a minified version of the code to 
> see what you're doing.

Sure, here it is:

```
auto getBoards()
{
	string[] boardList;

	auto url = baseUrl ~ "/api/v2/boards";
	auto http = HTTP(url);
	http.method = HTTP.Method.get;
	http.onReceive = (ubyte[] data) {
		auto content = cast(string) data[];
		boardList = strip(content, "[", "]").split(",");
		foreach (ref b; boardList) {
			b = strip(b, `"`);
		}

		return data.length;
	};

	http.perform();
	writeln(boardList);
	return boardList;
}
```

This is a member function of some class. It doesn't really have 
any fields, so I left if out. In it, I use curl library to getch 
some data and split it. Next, I try to use this function to get 
this list:

```
Fetcher fetcher = new Fetcher;

auto boards = fetcher.getBoards();
writeln(boards);
```
I printed array twice: inside the function and after return. Here 
is the output:
```
["a", "burg", "cyb", "d", "lain", "mu", "new", "tech", "test", 
"u", "v", "all"]
[x"F9"c, x"FA 01 00 00"c, "\0\0\0", "d", "lain", "mu", "new", 
"tech", "test", "u", "v", "all"]
```

As you can see, when outside of the funtion, first few elements 
of the array contain garbage. I would like to know both why this 
happens and how do I avoid it (i.e. what is the correct way of 
returning dynamic array).


More information about the Digitalmars-d-learn mailing list