Thread overview
Why does assign of string literal to fixed char array fail?
May 24, 2011
rthiebaud
May 24, 2011
bearophile
May 24, 2011
Jonathan M Davis
May 25, 2011
bearophile
May 24, 2011
The following program:

module main;
int main(string[] argv)
{
    char[20] a = "abc";
    return 0;
}

fails on Windows with:

First-chance exception at 0x7c812afb in ConsoleApp1.exe: 0xE0440001: 0xe0440001.

What is wrong?
May 24, 2011
rthiebaud:

> fails on Windows with:
> 
> First-chance exception at 0x7c812afb in ConsoleApp1.exe: 0xE0440001: 0xe0440001.
> 
> What is wrong?

To me it gives:
object.Exception@src\rt\arraycat.d(31): lengths don't match for array copy

When you assign to a fixed-sized array the source and destination lengths must match (this is not true for global variables. In Bugzilla I have asked to remove this special case, despite some people say this is not a special case).

Bye,
bearophile
May 24, 2011
On 2011-05-24 15:26, bearophile wrote:
> rthiebaud:
> > fails on Windows with:
> > 
> > First-chance exception at 0x7c812afb in ConsoleApp1.exe: 0xE0440001: 0xe0440001.
> > 
> > What is wrong?
> 
> To me it gives:
> object.Exception@src\rt\arraycat.d(31): lengths don't match for array copy
> 
> When you assign to a fixed-sized array the source and destination lengths must match (this is not true for global variables. In Bugzilla I have asked to remove this special case, despite some people say this is not a special case).

It may be useful, but it's still a special case. You're asking the compiler to copy an array of a particular length to an array of another length. I don't see how you could argue that it isn't a special case.

Regardless, even if it would be useful to allow such a copy, what would it do? If you have

char[20] a = "abc:

which characters are assigned the 'a', the 'b', and the 'c'? a[0 .. 3]? a[17 .. 20]? Characters in the middle of the char array? I really think that it makes perfect sense for the compiler to complain about this. It doesn't allow you to copy arrays of differing lengths anywhere else. Allowing it here would not only be a special case, but the syntax doesn't give you any way to say where the character literal is being copied to. I think that the compiler is definitely doing the correct thing here.

- Jonathan M Davis
May 25, 2011
Jonathan M Davis:

> > When you assign to a fixed-sized array the source and destination lengths must match (this is not true for global variables. In Bugzilla I have asked to remove this special case, despite some people say this is not a special case).

I think you have misunderstood me. This is my bug report/enhancement request: http://d.puremagic.com/issues/show_bug.cgi?id=3849

Bye,
bearophile