www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why does assign of string literal to fixed char array fail?

reply rthiebaud <thiebauddick2 aol.com> writes:
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
parent reply bearophile <bearophileHUGS lycos.com> writes:
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
parent reply "Jonathan M Davis" <jmdavisProg gmx.com> writes:
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 24 2011
parent bearophile <bearophileHUGS lycos.com> writes:
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
May 24 2011