On Saturday, 21 April 2018 at 07:37:50 UTC, Mike Franklin wrote:
Does D have some way to dynamically allocate on the stack? I'm
looking for something roughly equivalent to the following C
code.
int doSomething(size_t len)
{
char stackBuffer[len + 1];
doSomethingElse(stackBuffer);
}
Thanks,
Mike
The language itself doesn't have something, but you could use
`alloca`:
---
void doSomething(size_t len)
{
import core.stdc.stdlib, core.stdc.stdio;
auto stackBuffer = (cast(char*) alloca(char.sizeof * len +
1))[0 .. len + 1];
stackBuffer[0] = 'H';
stackBuffer[1] = '\0';
printf("%.*s", stackBuffer.ptr);
}
void main()
{
doSomething(2);
}
---