allow on stack with betterC

Vijay Nayar madric at gmail.com
Wed Oct 24 07:16:24 UTC 2018


On Tuesday, 23 October 2018 at 10:18:56 UTC, test wrote:
> On Tuesday, 23 October 2018 at 07:59:53 UTC, Dennis wrote:
>> On Tuesday, 23 October 2018 at 05:36:00 UTC, test wrote:
>>> correct if I am wrong,  I think malloc is on heap and is very 
>>> slow.
>>
>> Yes, you probably want a static array on the stack:
>>
>> ```
>> scope ubyte[4] tmp = void; // or a default value
>> ```
>>
>> This is analogous to this C (except scope):
>> ```
>> unsigned char tmp[4];
>> ```
>>
>> While 'new' is analogous to 'malloc'.
>
> I can not user static array because the length is a runtime 
> vars.

The nature of the stack is that every additional variable that is 
created will be added after the previous one (but lower in 
memory).  Because of this, the compiler needs to know how much 
space to reserve for your array.

A standard practice in C to get around this problem is to 
allocate an array on the stack (using a static array in D), but 
make the array set to the size of the maximum number of elements 
you may need.  It acts like a buffer.

When you are done loading data into it, you can either send it to 
a dynamic array if you want to keep it on the HEAP, or you can 
use a separate variable to keep track of the actual number of 
elements inside.


More information about the Digitalmars-d-learn mailing list