Dynamic Arrays Capacity

Salih Dincer salihdb at hotmail.com
Fri Jun 3 00:16:05 UTC 2022


On Thursday, 2 June 2022 at 08:14:40 UTC, Mike Parker wrote:
> 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.

I didn't know that, so maybe this example proves it; the 
following test code that Ali has started and I have developed:

```d
import std.range;
import std.stdio;

/* toggle array:

alias chr = char*;
auto data = [' '];/*/

alias chr = immutable(char*);
auto data = " ";//*/

void main()
{
   chr[] ptrs;
   data.fill(3, ptrs);

   writeln;
   foreach(ref ptr; ptrs)
   {
     " 0x".write(ptr);
   }
} /* Print Out:

  0:           0 1:          15 2:          31 3:          47
  0x55B07E227020 0x7F2391F9F000 0x7F2391FA0000 0x7F2391FA1000
//*/


void fill(R)(ref R mostRecent,
              int limit,
              ref chr[] ptrs)
{
   auto ptr = mostRecent.ptr;
   size_t capacity, depth;

   while (depth <= limit)
   {
     mostRecent ~= ElementType!R.init;

     if(ptr != mostRecent.ptr)
     {
       ptrs ~= ptr;
       depth.writef!"%2s: %11s"(capacity);
       depth++;
     }

     if (mostRecent.capacity != capacity)
     {
       ptr = mostRecent.ptr;
       capacity = mostRecent.capacity;
     }
   }
}
```

As for the result I got from this code: The array configured in 
the heap is copied to another memory region as soon as its 
capacity changes (0x5...20 >> 0x7...00). We get the same result 
in array. Just add the / character to the beginning of the 4th 
line to try it.

Thank you all very much for the replies; all of these open my 
mind.

SDB at 79


More information about the Digitalmars-d-learn mailing list