Why is there no literal size mismatch during compilation?

I have the following code:

import std.stdio; int main(string[] args) { int[3] my_array = [1, 2]; return 0; } 

This compiler compiles fine and then aborts at runtime, providing this error:

 arrays_init object.Exception@src /rt/arraycat.d(31): lengths don't match for array copy ---------------- arrays_init(_Dmain+0x64) [0x416bbc] arrays_init(extern (C) int rt.dmain2.main(int, char**).void runMain()+0x1c) [0x418c5c] arrays_init(extern (C) int rt.dmain2.main(int, char**).void tryExec(scope void delegate())+0x2a) [0x4185d6] arrays_init(extern (C) int rt.dmain2.main(int, char**).void runAll()+0x3b) [0x418ca3] arrays_init(extern (C) int rt.dmain2.main(int, char**).void tryExec(scope void delegate())+0x2a) [0x4185d6] arrays_init(main+0xd1) [0x418561] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed) [0x7f60bc41d30d] 

This works fine if the array literal has 3 elements, so obviously the array literal should fit the size of the static array. But should this not give a compilation error, since the size of both can be calculated at compile time?

+7
source share
3 answers

Array literals are of type T[] , that is, they are dynamic arrays that are not aware of their size at compile time.

Your code compiles for the same reason as compilation:

 void foo(int[] xs) { int[3] ys = xs; ... } 

The compiler just doesn't know how big xs .

In your case, the compiler can know at compile time, because all the information is there, but it will be higher and further than what the compiler should do. By interpreting the code strictly, there is no type mismatch, so it compiles.

Another side effect of array literals, which are dynamic arrays, is that the code you have will actually allocate memory. It allocates a dynamic array on the heap, copies it to a static array, and then you have to wait for the garbage collection cycle before the memory is recovered. This can be the cause of poor performance if you initialize such arrays in a compressed loop.

Again, the compiler can avoid the allocation, but DMD is at least not in the current version (2.060).

+9
source

This would be because the type [1, 2] (dynamic array) does not save the number of elements in the array, so by the time the compiler reaches the destination ( = ), it does not know how many elements are in the expression on the right side.

Simply put: the compiler is simply not smart enough.

+7
source

Probably due to this line:

 int[3] my_array = [1, 2]; 

on the left side you specify 3 values ​​in the ie array, you define a static array of 3 ints , but assign only two values.

Change it to:

 int[3] my_array = [1, 2, 3]; 

and the problem must be solved.

0
source

All Articles