Stupid question about AA. The following code works but I don't undrstand why?!

Uranuz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Apr 9 11:06:52 PDT 2016


On Saturday, 9 April 2016 at 16:44:06 UTC, ag0aep6g wrote:
> On 09.04.2016 18:13, Uranuz wrote:
>> http://dpaste.dzfl.pl/523781df67ab
>
> For reference, the code:
> ----
> import std.stdio;
>
> void main()
> {
> 	string[][string] mapka;
> 	
> 	string[]* mapElem = "item" in mapka; //Checking if I have item
> 	
> 	if( !mapElem )
> 		mapElem = &( mapka["item"] = [] ); //Creating empty element 
> inside map
> 	
> 	writeln( (*mapElem).capacity );
> 	
> 	//Appending should reallocate, so pointer to array should 
> change
> 	*mapElem ~= ["dog", "cat", "horse", "penguin", "fish", "frog"];
>
> 	//But AA still somehow knows the right pointer
> 	writeln(mapka);
> 	
> 	//It works, but I dont understand why?
> }
> ----
>
> mapElem is not a pointer to the elements of the array. It's a 
> pointer to the dynamic array structure which holds the pointer 
> to the data and the length. That means, the reallocation 
> doesn't change mapElem. It changes (*mapElem).ptr.

Thanks. It's clear now. AA holds not `array struct` itself 
inside, but pointer to it. So reallocation affects ptr to 
allocated memory but not pointer to `array struct`. I think 
that's it.


More information about the Digitalmars-d-learn mailing list