Variable lengh arrays of fixed length arrays

Oskar Linde oskar.lindeREM at OVEgmail.com
Thu Aug 3 23:50:40 PDT 2006


Derek Parnell wrote:
> On Fri, 4 Aug 2006 11:06:02 +1000, Derek Parnell wrote:
> 
>> What am I not understanding about these beasties...?
>>
>> This fails to compile ...
>>
>>  void main()
>>  {
>>   char[9][] sstore;  // A dynamic array of 9-char strings.
>>   char[9] astr;      // A single 9-char string.
>>
>>   // Extend the dynamic array.
>>   sstore.length = sstore.length + 1; 
>>
>>   // Copy the 9-char string to the last entry.
>>   sstore[$-1] = astr;  // **FAILS** 
>>  }
>>
>> The compiler message is ...
>>
>> test.d(10): cannot assign to static array (sstore)[cast(int)((__dollar) -
>> 1u)]
>>
>> In my mind, 'sstore' is *not* a static array. It is a dynamic array that
>> contains static arrays.
> 
> Ok, I found the syntax that works...
> 
>  import std.stdio;
>  void main()
>  {
>   char[9][] sstore;  // A dynamic array of 9-char strings.
>   char[9] astr;      // A single 9-char string.
> 
>   // The [] is required!
>   astr[] = "abcdefghi";
> 
>   // Extend the dynamic array.
>   sstore.length = sstore.length + 1;
> 
>   // Copy the 9-char string to the last entry.
>   sstore[$-1][] = astr;  
> 
>   writefln("%s %s", sstore.length, sstore[0]);
>  }
> 
> This is a stupid, stupid, stupid, wart on D.
> 
> Why does the syntax for fixed-length arrays have to be different to
> everything else? Makes template programming harder than it should be.

Yes, I have to put workarounds for static arrays in almost every array 
template function I make.

> 
> If one codes 
> 
>   char[9] X;
> 
>   X = "abcdefghi";
> 
> Why on Earth would the compiler think I'm trying to do anything else but
> copy the data from the literal to the array? I'm mean...what else can I do?
> I can't change the 'reference' because there is no reference with fixed
> length arrays - they just exist as RAM - they are not a pseudo struct like
> variable length arrays. 

Not being able to assign static arrays also means that you can't use 
them as a return type from functions.

> Walter, please justify this anomaly and why I should embrace this apparent
> lose of reason.

I guess there is a very obvious answer. This is all how static arrays 
work in C.

Making static arrays assignable (by copying the elements) means that 
static arrays would turn into value types, which IMHO is much better 
than their current state of being neither value nor reference types.

It would affect functions like:

void func(ubyte[10_000_000] buffer) {...}

But I doubt such cases are very common in D code. Calling extern(C) 
functions would still require the passing of a reference of course.

/Oskar



More information about the Digitalmars-d-learn mailing list