Minor issue - zero-length fixed size arrays in variable-sized structs..

Tim Matthews tim.matthews7 at gmail.com
Wed Jul 8 23:11:37 PDT 2009


Jarrett Billingsley wrote:
> I noticed in the spec on arrays that "A [fixed-size] 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.."  .......



It would be interesting if anyone has yet to find this useful. In c it 
could be used more directly. In D I think its not much use apart from 
the offset of property. It would be real bad to have to use it like this:

import std.stdio;

struct S
{
     int a;
     uint msgSize;
     char[0] message;
}

void setMessage(S* s, const char[] msg)
{
     (cast(char*)(s+S.message.offsetof))[0..s.msgSize] = msg[0..s.msgSize];
}

char[] getMessage(S* s)
{
     return (cast(char*)(s+S.message.offsetof))[0..s.msgSize];
}

S* createS(uint msgSize)
{
     S* s = cast(S*)((new ubyte[S.sizeof+msgSize]).ptr);
     s.msgSize = msgSize;
     return s;
}

void main()
{
     S* s = createS(5);
     setMessage(s, "hello");
     writeln(getMessage(s));
     setMessage(s, "world");
     writeln(getMessage(s));
}





More information about the Digitalmars-d mailing list