How to set array length for multidimensional static arrays

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 1 01:53:03 PST 2016


On Monday, February 01, 2016 07:42:56 Namal via Digitalmars-d-learn wrote:
> On Monday, 1 February 2016 at 07:41:33 UTC, Namal wrote:
> > I understand that I cannot pass a variable to the static array
> > like in C++, and have to use dynamic arrays. But how can I set
> > the length for them without using a loop?
>
> I mean std::vector in C++, not array.

I'm not sure what you're trying to do exactly. static arrays cannot be
resized. They're a fixed size that's known at compile time. And they're
nothing like std::vector at all. e.g.

   int[42] arr;

That array has 42 elements and will always have 42 elements. And you can't
do something like

    int[x] arr;

unless x is known at compile time (e.g. it's an enum).

Now, if you want something like std::vector, what you're probably looking
for is either dynamic arrays or std.container.Array. And dynamic arrays can
be allocated pretty much just like you'd do an array in C++ or Java. e.g.

    auto arr = new int[](42);

Or you can set its length directly. e.g.

    arr.length = 42;

If the new length is shorter than the current length, then it would be
identical to slicing the array and reassigning it to the original. e.g.

    arr = arr[0 .. 42];

And if the new length is longer, then each of the new elements is set to the
init value of the of the element type.

Or you can append elements with ~=, which would be like using push_back.
e.g.

    arr ~= 12;

And if you want to reserve a particular capacity for the dynamic array like
you might do with std::vector, then just use reserve. e.g.

    arr.reserve(42);

If you haven't yet, you really should read this article:

http://dlang.org/d-array-article.html

It really should help you understand dynamic arrays in D.

However, be warned that its terminology is a bit off. It uses the term
dynamic array for the GC-managed block of memory that a typical dynamic
array refers to (per the language spec, T[] is a dynamic array regardless of
what kind of memory it refers to, and a GC-managed block of memory has no
official term). Similarly, it uses the term slice for T[] rather than
dynamic array, and while a non-null dynamic array is a slice of memory of
some kind, the term slice is used for a lot more in D than just arrays.
Still, while its terminology is a bit wrong, the article is very good and
really a must read for anyone who wants to understand dynamic arrays in D.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list