how to initialize immutable 2 dim array

Michal Minich michal.minich at gmail.com
Sun Oct 31 11:26:42 PDT 2010


On Sun, 31 Oct 2010 17:46:29 +0000, Stewart Gordon wrote:

> On 31/10/2010 17:10, Michal Minich wrote:
>> I have global static array and I want it to initialize in module
>> constructor, but I get error. I there way to do it without using enum.
> 
> So you want to initialise it with data acquired at runtime, but make it
> immutable once initialised?
> 
>> immutable int[5][5] arr;
>>
>> static this () {
>>     arr = new int[5][5]; // Error: slice arr[] is not mutable
>> }
> 
> You have a more fundamental problem here.  arr is a static array, so you
> can't reference-assign it.
> 
> Best you can do is to either:
> 
> - initialise it statically, using CTFE or template metaprogramming to do
> the calculations, if they don't depend on getting external data
> 
> - use a dynamic array instead, and use .idup to populate it
> 
> - create a mutable pointer to it in the module constructor
>      int[5][5]* marr = cast(int[5][5]*) arr;
> and use that to populate the array.  But I'm not sure whether this leads
> to UB, and I still wish the means of casting away const or immutable
> were explicit.
> 
> Stewart.

I would rather use CTFE, but seems it isn't possible to work with 2 dim 
arrays at compile time. Also I need it to be static array, otherwise i 
would need to rewrite and test more code. 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
}


More information about the Digitalmars-d-learn mailing list