easier way?

bearophile bearophileHUGS at lycos.com
Wed Aug 25 17:53:28 PDT 2010


Jason Spencer:

> Stupid stuff, that won't account for varying row sizes (which isn't
> anything I need anyway.)  Things like (&array[$][$] -
> &array[0][0])/sizeof(array[0][0]), properly cast, etc.

Be careful, you risk doing a mess :-)
Dynamic arrays of the rows are not guaranteed to be contiguous, they have extra information at the end to support the append, there is the .ptr property that is better than using &, and be careful with sizeof(array) (that in D is a property) because it returns 2*size_t.sizeof for dynamic arrays if you aren't taking an item, or it returns the size in bytes for the whole array if it's a fixed-size one, so it's safer to use T.sizeof, where you know T is the element type.



> Yeah, maybe.  I guess the matrix thing will end up being what I really
> need.  In that case, I'd probably template on the element type and the
> size in each dimension, where latter dimensions are allowed to be of 0
> size.

Specifying the matrix sizes in the template is not useful, you obtain something very similar to a fixed sized array of fixed sized array.
I suggest you to create a templated struct where the template arguments are the element type and the number of dimensions.
Then you may overload many operators. Internally it allocates a single chunk of memory, so it contains the runtime size of all dimensions (so this struct supports dynamic reshaping too).


> I can never cast a dynamic array to a static array,

Is this OK for you? (this is not good code, and contains a runtime test, I don't remember if it's just an assert):

void foo(int[5] arr) {}
void main() {
    int[] sa = new int[5];
    int[5] da = sa[0 .. 5];
    foo(da);
}


Note that this code doesn't compile:

void foo(int[5] arr) {}
void main() {
    int[] sa = new int[5];
    foo(sa[0 .. 5]);
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list