dynamically allocating on the stack

Giles Bathgate giles.bathgate at gmail.com
Sat Apr 21 10:08:43 UTC 2018


On Saturday, 21 April 2018 at 07:57:41 UTC, Uknown wrote:
> The language itself doesn't have something, but you could use 
> `alloca`

I don't know if this little template function makes life easier:

------
pragma(inline, true)
ref T push(T)(size_t len)
{
     import core.stdc.stdlib, core.stdc.stdio;

     return *cast(T*)alloca(T.sizeof * len);
}


void doSomething(size_t len)
{
     auto stackBuffer = push!char(len+1);
     stackBuffer[0] = 'H';
     stackBuffer[1] = '\0';
     printf("%.*s", stackBuffer.ptr);
}

void main()
{
     doSomething(2);
}
------




More information about the Digitalmars-d-learn mailing list