Error: span violation in programming D

I have a dynamic array in structure and a method that uses a dynamic array. The problem is that I get a range violation error when starting the program. However, when I create a new dynamic array inside the method, it works fine. The following code is causing the problem.

struct MyStr { int[] frontArr; this(int max = 10) { frontArr = new int[10]; } void push(int x) { frontArr[0] = x; } } void main() { MyStr s; s.push(5); } 

However, this works:

 struct MyStr { int[] frontArr; this(int max = 10) { frontArr = new int[10]; } void push(int x) { frontArr = new int[10]; // <---Add this line frontArr[0] = x; } } void main() { MyStr s; s.push(5); } 

I basically add this line to check the scope. It seems that the initialized FrontArr cannot be seen in the push (int x) method. Any explanation?

Thanks in advance.

+4
source share
3 answers

Initialization of structures must be guaranteed. You don’t want the struct construct to throw an exception by default. For this reason, D does not support default constructors in structures. Imagine if

 MyStr s; 

led to the exception being thrown. Instead, D provides its own default constructor, which initializes all fields for the init property. In your case, you do not call your constructor and simply use the provided default values, which means that frontArr is never initialized. You want something like:

 void main() { MyStr s = MyStr(10); s.push(5); } 

The compiler error should probably have default values ​​for all parameters of the constructor constructor. Bugzilla

+6
source

I could be wrong (I did not use D after a while, so it's a little rusty.), But FrontArr is an array, and in your code example you are trying to assign it a pointer to an array. Dynamic arrays work like this (note copied by tutorial D found here )

 int[] MyArray; MyArray.length = 3; 
0
source

For some reason, D does not support constructor constructors that require no arguments, either use opCall or remove the default initializer on this()

 struct MyStr { int[] frontArr; static MyStr opCall() { MyStr s; s.frontArr = new int[10]; return s; } void push(int x) { frontArr[0] = x; } } 
0
source

All Articles