Assigning to slice of array

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Mar 1 23:17:11 UTC 2018


On Thursday, March 01, 2018 22:57:16 Jamie via Digitalmars-d-learn wrote:
> On Thursday, 1 March 2018 at 21:34:41 UTC, Jonathan M Davis wrote:
> > Don't put the indices within the brackets. What you want is
> >
> > auto arr = new int[][][](3, 2, 1);
>
> Okay thanks, but I don't understand what is the issue with having
> static arrays there instead? My functionality didn't change when
> I replaced the single line with your line?
>
> And I couldn't resize either of them with array.length, which is
> also something I would like.
> Thanks

static arrays have a fixed size, so you can't resize them with any operation
- including setting their length. Static arrays are value types, so when
they're copied, the whole thing is copied, whereas with a dynamic array is
just a pointer and a length, so copying it just slices the dynamic array to
give you another dynamic array. It's just copying the pointer and the
length. A dynamic array is effectively

struct DynamicArray(T)
{
    size_t length;
    T* ptr;
}

whereas a static array is an actual buffer that sits wherever it's declared
(on the stack if it's a local variable).

So, something like

auto arr = new int[][][](3, 2, 1);
arr.length = 4;
arr[0].length = 5;
arr[0][0].length = 6;

is legal, but something like

auto arr = new int[3][2][1];
arr.length = 4; // this one is still legal, since it's a dynamic array
arr[0].length = 5;
arr[0][0].length = 6;

is not legal.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list