Zero-length static array spec

Iain Buclaw via Digitalmars-d digitalmars-d at puremagic.com
Sat Feb 7 04:21:52 PST 2015


On 7 February 2015 at 10:56, FG via Digitalmars-d
<digitalmars-d at puremagic.com> wrote:
> On 2015-02-07 at 00:42, David Nadlinger wrote:
>>
>> Imagine you have this in your program:
>>
>> ---
>> void foo() {
>>    int[0] a0;
>>    int[0] a1;
>>    ...
>>    int[0] a99;
>>
>>    // Do something with them.
>> }
>> ---
>>
>> How do you choose the addresses for a0 through a99 so that they are
>> distinct, but you don't end up allocating 100 bytes of stack memory?
>
>
>
> Forgive my ignorance and perhaps not seeing the whole picture, but when I
> read this:
>
>> A static array with a dimension of 0 is allowed, but no space is allocated
>> for it. It's useful as the last member of a variable length struct...
>
>
> i am convinced that a0, ..., a99 are not variables but rather *labels* and
> should point to *the same address* of whatever could be put in that place
> (with 1-byte alignment). I do not understand why would they ever point to
> different places. Wouldn't that make them useless when used in structs like
> the following one (or to access stack, like above)?
>
>     struct Packet {
>         int a, b, c, length;
>         ubyte[0] data;
>         ubyte[0] payload;  // just a superfluous alias to data
>     }
>     unittest {
>         Packet p;
>         assert(p.sizeof == 16);
>         assert(&p + 1 == cast(void*) &p.data);
>         assert(&p + 1 == cast(void*) &p.payload);
>     }
>
> As for passing it around, it doesn't make sense, it is like passing an
> argument of type void, so shouldn't be allowed. Only a pointer to a
> zero-length array or a specified element would be fine:
>
>     foo(&p.data)    // fine, ubyte*

This is OK - gets passed as ubyte*

>     bar(p.data[i])  // fine, ubyte (or memory violation)

This is OK - gets passed as ubyte - though will throw arrayBounds
error unless -noboundschecks.

>     xxx(p.data)     // ERROR, makes no sense, shouldn't compile

This is OK - gets passed as ubyte[] - the dynamic array will have a
length of '0' and the ptr to &p.data.

Iain.


More information about the Digitalmars-d mailing list