how to initialize immutable 2 dim array

bearophile bearophileHUGS at lycos.com
Sun Oct 31 11:53:42 PDT 2010


Michal Minich:

> I like the simple workaround 
> with using mutable pointer, but I'm getting access violation error even 
> when arr is mutable ... and really don't understand why... :(
> 
> int[256][256] arr;
> 
> static this () {
> 
>     int[256][256]* pArr = &arr;
>         
>     for (int y = 0; y <= 255; y++)
>         for (int x = 0; x <= 255; x++)
>             pArr[x][y] = x * y; // Access violation when x = 2 and y = 0
> }

You need to put a bit more thought on your code:

import std.stdio: writeln;

int[256][256] arr;

static this () {
    auto pArr = &arr;
    foreach (y; 0 .. (*pArr)[0].length)
        foreach (x; 0 .. (*pArr).length)
            (*pArr)[x][y] = x * y;
}

void main() {
    writeln(arr);
}

(I have just fixed your code locally, I don't know what you are doing and why you are using a pointer to a fixed sized array, it's an unusual idiom in D.)

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list