arrays and .sizeof

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Thu Aug 11 00:34:16 PDT 2011


On Tue, 09 Aug 2011 14:38:21 +0200, 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.

I would say that you are using .sizeof wrongly.  You should not use it to 
get the size of an array, be it static or not.  You should *only* use 
x.sizeof when you want to know the size of the variable x, not of 
whatever x points to.

-Lars


More information about the Digitalmars-d mailing list