Appending to multidimensional dynamic array
Rikki Cattermole via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat May 30 05:54:16 PDT 2015
On 31/05/2015 12:41 a.m., kerdemdemir wrote:
> I want to append a 2D array to my 3D array. I expect it should be same
> as int[] arr; arr ~= 3;
>
> void readInput()
> {
> char[][][] candidate;
> char[] buff;
> size_t counter = 0;
> while ( stdin.readln(buff) )
> {
> char[][] line = buff.chomp().split();
> writeln(line);
>
> candidate ~= line;
> writeln(candidate);
> if (++counter > 1 ) break;
> }
> }
>
> And I send the inputs below
>
> 201212?4 64
> 20121235 93
> I expect a output like
>
> [["201212?4", "64"], ["20121235", "93"]]
> But instead I see
>
> [["20121235", "93"], ["20121235", "93"]]
>
> In short :
> =~ replaces all the elements in the array with the last added. Where am
> I doing wrong? How can I meet my expectation?
>
>
> By the way I am posting the same question to stackoverflow at the same
> time. Does sending questions to stackoverflow as well as here not
> desirable for D community? If so I will just write here.
stackoverflow isn't normally looked at by those in the D community.
In your case its pretty simple. The buffer is being reused. So same
memory being added multiple times to the candidate.
Just slap on a .dup when adding it.
It'll duplicate the contents in new memory so it won't be assigned on
top of.
More information about the Digitalmars-d-learn
mailing list