arrays and .sizeof

Jacob Carlborg doob at me.com
Tue Aug 9 06:34:46 PDT 2011


On 2011-08-09 14:38, Trass3r 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.

You can implement your own function that behaves differently for static 
and dynamic arrays, call it "sizeOf" or something like that and it will 
almost look built-in.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list