Variable lengh arrays of fixed length arrays

Derek Parnell derek at nomail.afraid.org
Thu Aug 3 18:16:14 PDT 2006


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.

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. 

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

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
4/08/2006 11:09:52 AM



More information about the Digitalmars-d-learn mailing list