Zero length arrays in D
H. S. Teoh
hsteoh at quickfur.ath.cx
Mon Feb 18 16:33:58 UTC 2019
On Mon, Feb 18, 2019 at 01:34:37PM +0000, Eduard Staniloiu via Digitalmars-d-learn wrote:
> Hello
>
> According to the spec[0], D supports zero length arrays [1].
Huh. I didn't even know D was supposed to support this. I found a few
examples of this usage in Adam Ruppe's arsd code, where the zero-length
array is sliced as you indicated:
struct X {
int[0] data;
}
X* x = ...;
int[] arr = x.data.ptr[0 .. n];
arr[i] = ...;
[...]
> Attempting to use the zero-length array results in a compiler error
>
> `a.contents[2]` -> Error: array index 2 is out of bounds
> (*a).contents[0 .. 0]
Yeah this needs to be explicated in the docs / spec.
> The way I've used around this error is "safely" break/trick the type
> system
>
> ```
> int *p = a.contents.ptr;
> int[] p_cont = p[0 .. n];
> p_cont[2] = 10; // fine
> ```
>
> Is this the intended way of working with zero length arrays?
[...]
No idea. But it's probably the only way of actually using them right
now. :-D The spec / docs need to be updated.
T
--
Long, long ago, the ancient Chinese invented a device that lets them see through walls. It was called the "window".
More information about the Digitalmars-d-learn
mailing list