arrays and .sizeof

bearophile bearophileHUGS at lycos.com
Tue Aug 9 06:21:05 PDT 2011


Trass3r:

> 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.

What if the array is an associative one? Or a user-defined struct that represents a 2D matrix, that contains a pointer to heap memory? sizeof is not what you think it is. It doesn't return the whole memory used by a data structure, just its size on the stack. If you want to know the whole memory used by a data structure that contains references you need a function written by yourself (one idea is to add a .memory attribute to every built-in type that returns the whole memory used by it, but it's hard to do because data structures can share part of their memory, they don't need to always own memory).

Bye,
bearophile


More information about the Digitalmars-d mailing list