arrays and .sizeof

Pelle pelle.mansson at gmail.com
Tue Aug 9 07:07:00 PDT 2011


On Tue, 09 Aug 2011 14:38:21 +0200, Trass3r <un at known.com> wrote:

> I've encountered this problem several times now and almost always it  
> takes hours or days to reduce crashes down to this.
> The sizeof property works as expected for static arrays, but as soon as  
> you change the array to a dynamic one (e.g. cause it became too big to  
> stay on the stack)
> .sizeof doesn't return .length * elem.sizeof anymore but only the size  
> of the struct consisting of .ptr and .length.
>
> This is really error-prone and I need the actual size of an array while  
> interfacing with C a lot.
> Any way to avoid this? Maybe a dmd warning if possible?
>
> Please don't "just use .length * elem.sizeof" me. It's cumbersome and a  
> bit error-prone as well. If you hard-code the element type and the type  
> changes later -> bang.
> I know I could use a function but this doesn't change the problem that  
> .sizeof works perfectly for static arrays and silently crashes when  
> changed to a dynamic one.

size_t memSize(T)(T[] ts) { return t.length * T.sizeof; }

And then never use .sizeof for that purpose again.


More information about the Digitalmars-d mailing list