Allocating a fixed-size array on the heap

David Wilson dw at botanicus.net
Wed Jan 30 07:41:01 PST 2008


On 1/30/08, Jarrett Billingsley <kb3ctd2 at yahoo.com> wrote:
> So, in the process of answering another thread, I realized that it doesn't
> entirely seem possible to allocate a fixed-size array on the heap through
> normal means.  That is,  the following is legal:
>
> float[4] a;
> float[4]* b = &a;
>
> But:
>
> float[4]* c = new float[4];
>
> "Waiit," says the compiler, "the type of 'new float[4]' is float[]."
>
> So here some syntactic sugar is getting in the way of writing what I mean!
>
> I've come up with this:
>
> T* alloc(T)()
> {
>     struct S
>     {
>         T t;
>     }
>
>     return &(new S).t;
> }
>
> ..
>
> float[4]* d = alloc!(float[4]);
>
> but that seems awfully hackish.

As I understand it, a variable of the type float[4] will already be a
reference pointing to the heap. The pointer syntax I do not
understand, and it doesn't seem particularly well documented.

As I understand it,

   float[4] a = new float[4];
   float[4]* b = &a;

b is a word-sized pointer to a, which is 2 words (ptr, length). The
first word, ptr, is pointing to the heap.
>
> Am I missing something or is this just yet another instance of how
> fixed-size arrays aren't treated as first-class citizens?
>

Either you're missing something or I am. I think the pointer support
is purely for C compatibility (but I may be terribly wrong).

>
>



More information about the Digitalmars-d mailing list