array questions

bearophile bearophileHUGS at lycos.com
Sun Jan 11 23:07:28 PST 2009


yes:

> is it possible to make a dynamic array less dynamic?
> int[][] array;
> array[0].length = 10; //has to be set at runtime
> writefln(array[1].length); // writes also 10
> Because I now have to loop through the whole array to check for correct size.

If you are using normal D dynamic arrays you have to loop through the whole array to check for correct size.
Otherwise you have to create a new and different data structure, an array that is guaranteed to be rectangular. Probably there are already such data structure done by someone else (the downside is that DMD may handle them less efficiently. The up side is that the resulting memory allocated is probably contiguous, that leads to better cache coherence, less memory wasted, and ability to quickly reshape the matrix on the fly).
Built-in dynamic arrays are just one of the many possible kinds of arrays a programmer may need. I think the current D design is good enough: a very common and flexible case is built-in, and you can create the other different data structures by yourself (or you can import them from a lib like Tango).


> also, can this be done?
> int size;
> size = 10; //runtime
> void function( int[size][] array){}

The size of a dynamic array is an information known only at runtime, so the D type system is unable to know it at compile time. So for the D type system is impossible to perform that control at compile time.
What you ask may be done by a more powerful type system in special situations (when the compiler can infer at compile time the size), but you need a more powerful type system.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list