new T[size] vs .reserve - alloca

Nick Treleaven ntrel-public at yahoo.co.uk
Tue Feb 5 13:13:27 PST 2013


On 05/02/2013 21:02, monarch_dodra wrote:
> On Tuesday, 5 February 2013 at 20:47:46 UTC, Nick Treleaven wrote:
>> On 05/02/2013 16:47, monarch_dodra wrote:
>>> T[] stack(T, alias N)(void* m = alloca(T.sizeof * N))
>>> {
>>>     return (cast(T*)m)[0 .. N];
>>> }
>>
>> This works if you know N at compile-time. But there doesn't seem to be
>> a way to wrap alloca to accept a runtime-only value, e.g.:
>>
>> // allocate as many ints as command-line parameters
>> int[] arr = stack!int(args.length);
>
> I don't have access to my compiler, but that *should*work. Did you try
> it? BTW, the syntax would be:
>
> int[] arr = stack!(int, args.length)();

I've just tried it with dmd 2.059 (haven't upgraded yet). I got:

Error: variable args cannot be read at compile time

void main(string[] args)
{
     int[] arr = stack!(int, args.length)();
}


More information about the Digitalmars-d-learn mailing list