www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Zero length arrays in D

reply Eduard Staniloiu <edi33416 gmail.com> writes:
Hello

According to the spec[0], D supports zero length arrays [1].

I have given this a shot at https://run.dlang.io/is/PwbPxJ

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]

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?

Cheers,
Edi


[0] - https://dlang.org/spec/arrays.html#static-arrays, best 
practices pt 2
[1] - 
https://gcc.gnu.org/onlinedocs/gcc-4.7.4/gcc/Zero-Length.html
Feb 18 2019
parent "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
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".
Feb 18 2019