Dynamic Arrays Capacity

Mike Parker aldacron at gmail.com
Thu Jun 2 08:14:40 UTC 2022


On Thursday, 2 June 2022 at 05:04:03 UTC, Salih Dincer wrote:
> Hi,
>
> Do I misunderstand? A dynamic array is allocated memory 
> according to the `nextpow2()` algorithm(-1 lapse); strings, on 
> the other hand, don't behave like this...
>
> ```d
>   string str = "0123456789ABCDEF";
>   char[] chr = str.dup;
>
>   assert(str.length == 16);
>   assert(str.capacity == 0);
>
>   import std.math: thus = nextPow2; //.algebraic
>
>   assert(chr.capacity == thus(str.length) - 1);
>   assert(chr.capacity == 31);

You've initialized `str` with a string literal. No memory is 
allocated for these from the GC. They're stored in the binary, 
meaning they're loaded into memory from disk by the OS. So 
`str.ptr` points to a static memory location that's a fixed size, 
hence no extra capacity.

`chr` is allocated from the GC using whatever algorithm is 
implemented in the runtime. That it happens to be any given 
algorithm is an implementation detail that could change in any 
release.

> ```
>
> Also, `.ptr` keeps the address of the most recent first 
> element, right?
>

More specifically, it points to the starting address of the 
allocated block of memory.


More information about the Digitalmars-d-learn mailing list